5

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?

Community
  • 1
  • 1
Maciej Stachowski
  • 1,708
  • 10
  • 19

1 Answers1

2

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) {}
Community
  • 1
  • 1
Karthik T
  • 31,456
  • 5
  • 68
  • 87
  • So, that means that all the classes inheriting from Derived1/2 or any of their subclasses have to call Base constructor? My love for C++ has just shrunk a little. – Maciej Stachowski Jan 23 '13 at 01:54