| Topic: |
DEVELOP > c-Plus-Plus |
| User: |
"lok" |
| Date: |
17 Nov 2003 12:21:47 AM |
| Object: |
Question about virtual inheritance |
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() ?
.
|
|
| User: "tom_usenet" |
|
| Title: Re: Question about virtual inheritance |
17 Nov 2003 07:27:16 AM |
|
|
On 16 Nov 2003 22:21:47 -0800, (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
.
|
|
|
| User: "tom_usenet" |
|
| Title: Re: Question about virtual inheritance |
17 Nov 2003 09:18:36 AM |
|
|
On Mon, 17 Nov 2003 13:27:16 +0000, tom_usenet
<tom_usenet@hotmail.com> wrote:
KeyInfo, then PairInfo.
I meant AlgInfo rather than PairInfo of course.
Tom
.
|
|
|
|
|

|
Related Articles |
|
|