Inheritance and constructor problem

S

Stefan Istrate

I have the following code:

#include <iostream>
using namespace std;

class B {
int x;
public: B(int i) {x = i;}
};

class D1: virtual B {
public: D1(int i): B(i){}
};

class D2: virtual B {
public: D2(int i): B(i){}
};

class D3: B {
public: D3(int i): B(i){}
};

class D4: private B {
public: D4(int i): B(i){}
};

class D5: virtual public B {
public: D5(int i): B(i){}
};

class M1: D1, public D2, D3, private D4, virtual D5 {
public:
M1(): D5(5), D1(1), D2(2), D3(3), D4(4) {}
};

int main() {
M1 x;
}

This doesn't work and I don't know why. It seems that a constructor of
class B is called without parameters, but I can't figure where. Any
suggestions would be appreciated.

Thank you,
Stefan Istrate
 
M

Michael DOUBEZ

Stefan Istrate a écrit :
I have the following code: [snipped]
class B ;
class D1: virtual B {
class D2: virtual B {
class D3: B {
class D4: private B {
class D5: virtual public B {
class M1: D1, public D2, D3, private D4, virtual D5 {
public:
M1(): D5(5), D1(1), D2(2), D3(3), D4(4) {}
};

int main() {
M1 x;
}

This doesn't work and I don't know why. It seems that a constructor of
class B is called without parameters, but I can't figure where. Any
suggestions would be appreciated.

Since you virtually inherit B, you must indicate how is initialized the
common B.

M1(): D5(5), D1(1), D2(2), D3(3), D4(4), B(0) {}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top