Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtual inheritance and parametrized constructors [duplicate]

Tags:

c++

Possible Duplicate:
Default constructor and virtual inheritance

class Base
{
private:
    int number;
protected:
    Base(int n) : number(n) {}
public:
    virtual void write() {cout << number;}     
};

class Derived1 : virtual public Base
{
private:
    int number;
protected:
    Derived1(int n, int n2) : Base(n), number(n2) {}
public:
    virtual void write() {Base::write(); cout << number;}
};

class Derived2 : virtual public Base
{
private:
    int number;
protected:
    Derived2(int n, int n2) : Base(n), number(n2) {}
public:
    virtual void write() {Base::write(); cout << number;}
};

class Problematic : public Derived1, public Derived2
{
private:
    int number;
public:
    Problematic(int n, int n2, int n3, int n4) : Derived1(n, n2), Derived2(n, n3), number(n4) {}
    virtual void write() {Derived1::write(); Derived2::write(); cout << number;}
};

int main()
{
    Base* obj = new Problematic(1, 2, 3, 4);
    obj->write();
}

In other words:

Base
| \
|  \
|   \
|    \
D1   D2
|    /
|   /
|  /
| /
Problematic

I'm trying to get "1 2 1 3 4" on the output. The compiler, however, keeps complaining that I need a parameterless constructor in Base, but when I add one, the "1" turns to garbage. Any ideas on how to approach it? Is it even possible to solve the diamond pattern using a parametrized constructor?

like image 773
Maciej Stachowski Avatar asked Nov 04 '22 06:11

Maciej Stachowski


1 Answers

Take a look at Calling a virtual base class's overloaded constructor, it looks like if the inheritance is virtual, the most derived class must call the base class constructor.

Problematic(int n, int n2, int n3, int n4) : Derived1(n, n2), Derived2(n, n3), Base(n), number(n4) {}
like image 132
Karthik T Avatar answered Nov 15 '22 04:11

Karthik T