Initialization of virtual bases

D

Dave Theese

Hello all,

The code example below has proper behavior (of course), but I'm trying to
understand how the behavior is brought about. Specifically, what happens to
B's and C's initialization of A??? Is it just ignored even though it
explicitly appears in the code?

Thanks,
Dave

#include <iostream>

using namespace std;

class A
{
public:
A(int d): data(d)
{
cout << "data initialized to " << d << endl;
}

private:
int data;
};

class B: virtual public A
{
public:
B(int d): A(d)
{
}
};

class C: virtual public A
{
public:
C(int d): A(d)
{
}
};

class D: public B, public C
{
public:
D(int d): A(d), B(d + 1), C(d + 2)
{
}
};

int main(void)
{
// Displays "data initialized to 1"
D foo(1);

return 0;
}
 
J

John Harrison

Dave Theese said:
Hello all,

The code example below has proper behavior (of course), but I'm trying to
understand how the behavior is brought about. Specifically, what happens to
B's and C's initialization of A??? Is it just ignored even though it
explicitly appears in the code?

Thanks,
Dave

#include <iostream>

using namespace std;

class A
{
public:
A(int d): data(d)
{
cout << "data initialized to " << d << endl;
}

private:
int data;
};

class B: virtual public A
{
public:
B(int d): A(d)
{
}
};

class C: virtual public A
{
public:
C(int d): A(d)
{
}
};

class D: public B, public C
{
public:
D(int d): A(d), B(d + 1), C(d + 2)
{
}
};

int main(void)
{
// Displays "data initialized to 1"
D foo(1);

return 0;
}

Yes I believe so, virtual base classes are initialised by the more derived
object (or something like that). So if you created a B or a C object then B
or C would be responsible for initialising A.

john
 

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,777
Messages
2,569,604
Members
45,227
Latest member
Daniella65

Latest Threads

Top