Nitixx Nitixx - 3 months ago 7
C++ Question

Using this slice my object

I have some difficulties using

this
, it seems to slice my derived class. This example will help me to explain my problem.

class A
{
A() {
OtherClass(*this);
}

virtual doSomething() = 0;
}

class B : public A
{
B() : A() {}

doSomething() override {
std::cout << "Hi!" << std::endl;
}
}

class OtherClass()
{
OtherClass(A &a) {
a.doSomething();
}
}


After some investigation it seems like that using
*this
slice the class
B
. And then
OtherClass
will call a pure virtual method on
A
. I'm wrong? Should I make the
OtherClass(*this)
, after the Initialization of the
B
class?

Answer

A's constructor invokes OtherClass's constructor, which invokes A's pure virtual method.

Unfortunately, since A's subclass, which implements this virtual method, hasn't been constructed yet, the result is undefined behavior.

Remember: superclasses get constructed before subclasses. Before B can get constructed (and thus implement the pure virtual method), it's superclass, A, needs to get constructed fully. As a part of that process, of course, A's constructor gets invoked.