Question about virtual inheritance

L

lok

consider follow simple code:

class Base {
protected:
int m_nAddr;
public:
Base(int addr_): m_nAddr(addr_) {}
virtual ~Base() {}
virtual int GetData() const = 0;
};

class KeyInfo: virtual public Base {
protected:
int m_nKey;
public:
KeyInfo(int addr_, int key_): Base(addr_), m_nKey(key_) {}

int GetData() const {
return m_nKey;
}
};

class AlgInfo: virtual public Base {
protected:
int m_nAlg;
public:
AlgInfo(int addr_, int alg_): Base(addr_), m_nAlg(alg) {}

void GetData() const {
return m_nAlg;
}
};

class PairInfo: public KeyInfo, public AlgInfo {
protected:
int m_nPair;
public:
PairInfo(int addr_, int key_, int alg_, int pair_)
: Base(addr_), KeyInfo(addr_, key_), AlgInfo(addr_, alg_),
m_nPair(pair_) {}

void GetData() const {
return m_nPair;
}
};


Q1. When an PairInfo is created, before its constructor PairInfo()
called, compiler will call Base(), KeyInfo() & AlgInfo, in which order
these 3 constructor will be called ?

Q2. As it is virtual inheritance, PairInfo only have a copy of Base,
so when constructor KeyInfo() and AlgInfo() are called, they will not
call their own parent class constructor Base() ?
 
T

tom_usenet

On 16 Nov 2003 22:21:47 -0800, (e-mail address removed) (lok) wrote:

Example condensed to:

Base
/ \
KeyInfo AlgInfo
\ /
PairInfo

[SNIP]
Q1. When an PairInfo is created, before its constructor PairInfo()
called, compiler will call Base(), KeyInfo() & AlgInfo, in which order
these 3 constructor will be called ?

Virtual bases are initialized first, based on the order they appear in
the inheritence list. Then direct base classes are initialized in the
order you listed them in the base specifier list. So its Base, then
KeyInfo, then PairInfo.
Q2. As it is virtual inheritance, PairInfo only have a copy of Base,
so when constructor KeyInfo() and AlgInfo() are called, they will not
call their own parent class constructor Base() ?

No. Only the most derived sub object initializes virtual bases, hence
the Base parts of the initializer lists of KeyInfo and AlgInfo are
ignored when a PairInfo is constructed.

Tom
 

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

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,017
Latest member
GreenAcreCBDGummiesReview

Latest Threads

Top