I have three classes as you can see in the code below. Notice how I have written the copy constructors.
#include <iostream>
class Abstract
{
public:
Abstract(){};
Abstract( const Abstract& other ): mA(other.mA){};
virtual ~Abstract(){};
void setA(double inA){mA = inA;};
double getA(){return mA;};
virtual void isAbstract() = 0;
protected:
double mA;
};
class Parent : public virtual Abstract
{
public:
Parent(){};
Parent( const Parent& other ): Abstract(other){};
virtual ~Parent(){};
};
class Child : public virtual Parent
{
public:
Child(){};
Child( const Child& other ): Parent(other){};
virtual ~Child(){};
void isAbstract(){};
};
int main()
{
Child child1;
child1.setA(5);
Child childCopy(child1);
std::cout << childCopy.getA() << std::endl;
return 0;
}
Now why Abstract()
gets called instead of the copy constructor Abstract( const Abstract& other )
when childCopy
is being constructed?
Shouldn't Child(other)
call Parent(other)
? And shouldn't Parent(other)
in turn call Abstract(other)
?
Virtual base classes can only be initialized by the most derived class. Calls to a constructor of a virtual base from a non most-derived class are ignored and replaced with default constructor calls. This is to ensure that the virtual base subobject is initialized only once:
The correct code should place the constructor call in the most derived class' ctor-initializer: