Virtual base class

Joined
Feb 12, 2008
Messages
108
Reaction score
0
Hello everyone,


Here is the related C++ Spec and my test code. I think virtual base class, no matter direct virtual base class or not, will always be constructed before non-virtual class (including non-virtual direct base class), correct?

Another question is, what means "and only for the constructor of the most derived class as described below" in related Spec statements?

Spec:

--------------------
12.6.2 Initializing bases and members [class.base.init]

5 Initialization shall proceed in the following order:
— First, and only for the constructor of the most derived class as described below, virtual base classes shall
be initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph
of base classes, where “left-to-right” is the order of appearance of the base class names in the derived
class base-specifier-list.
— Then, direct base classes shall be initialized in declaration order as they appear in the base-specifier-list
(regardless of the order of the mem-initializers).
— Then, nonstatic data members shall be initialized in the order they were declared in the class definition
(again regardless of the order of the mem-initializers).
— Finally, the body of the constructor is executed.
[Note: the declaration order is mandated to ensure that base and member subobjects are destroyed in the
reverse order of initialization. ]
--------------------

Code:
/*
output
constructor B1
constructor B2
constructor D2
constructor D1
constructor D3
*/

#include <iostream>

using namespace std;

class B1 {
public:
	 B1()
	 {
		 cout << "constructor B1 " << endl;
	 }
};

class B2 {
public:
	 B2()
	 {
		 cout << "constructor B2 " << endl;
	 }
};

class D1 : virtual public B1 {
public:
	 D1()
	 {
		 cout << "constructor D1 " << endl;
	 }
};

class D2 : public virtual B1, public B2 {
public:
	 D2()
	 {
		 cout << "constructor D2 " << endl;
	 }
};

class D3 : public D1, virtual public D2 {
public:
	 D3()
	 {
		 cout << "constructor D3 " << endl;
	 }
};

int main()
{
	D3 d;
	return 0;
}


thanks in advance,
George
 

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