S
S
sddvxd2018-04-20 21:22:58
OOP
sddvxd, 2018-04-20 21:22:58

Why create a constructor in an abstract base class?

Hello!
In the literature that I read, the author creates a constructor in ABC:

class ABC{
public:
    ABC(tralala &, trololo);
    ....
};

Derived class:
class Test : public ABC{
public:
    Test(trololo, tututu &):ABC(tututu &, trololo);
};

Question: why create an explicit constructor for ABK, if its object cannot be created (if there is a pure virtual function, of course) and the second question: what kind of strange call to the ABK constructor in the derived class constructor? Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mercury13, 2018-04-20
@sddvxd

Abstract classes are divided into interfaces and partially implemented. The line between them is as follows:
• The interface has no data.
• For an interface, all non-abstract virtual methods represent either the reference behavior or the most common implementation. In both cases, if anything, they should not be expanded, but rewritten from scratch.
So, for interfaces, such constructors, of course, are not necessary.
For example, between an abstract stream and a Win32 file, there can be such a hierarchy: Stream → HandleStream → File. Stream is an interface, even if there is something like

// virtual
unsigned long long Stream::remainder() const { return size() - pos(); }

HandleStream already contains data (a Win32 handle), and it is already a partially implemented class that revolves around this handle: in the destructor, the CloseHandle call, the constructor can take a handle received in some "left" way.
HandleStream::HandleStream(HANDLE aHandle) : fHandle(aHandle) {}
HandleStream::~HandleStream() { close(); }

void HandleStream::close()
{
  if (Handle != INVALID_HANDLE)  { // не помню, как там эта константа в Win32
    CloseHandle(fHandle);
    fHandle = INVALID_HANDLE;
  }
}

In such semi-realized classes, of course, the constructor can initialize the data that is there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question