By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,819 Members | 1,185 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,819 IT Pros & Developers. It's quick & easy.

Initialization of virtual bases

P: n/a
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;
}

Jul 19 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a

"Dave Theese" <ch**********@yahoo.com> wrote in message
news:QSX1b.7781$QT5.1646@fed1read02...
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
Jul 19 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.