C++: Trying to understand initialiser lists with inheritance.
Hi all. I'm working on improving my C++, and I've just come across something that is really puzzling me.
I have the following class hierarchy:
class A
{
public:
A(Stuff *pStuff);
};
class AA : public A
{
public:
AA(Stuff *pStuff);
};
class AAA : public AA
{
public:
AAA(Stuff *pStuff);
};
Constructors for AA and AAA call their base class constructors through their initialiser lists:
AA::AA(Stuff *pStuff)
: A(pStuff)
{
...
}
AAA::AAA(Stuff *pStuff)
: AA(pStuff)
{
...
}
When I throw this at the compiler (Microsoft Visual Studio 2005), it rejects it at AAA::AAA, as it says it can't find a default constructor for A. This is what puzzles me.
My definition of AAA::AAA tells the compiler which constructor I'm using for AA - but shouldn't THAT tell it which constructor I want to use for A?
I've found two ways to make the compiler happy, but I don't understand things well enough to be all that comfortable yet with either method (one, because I simply don't understand at all what's going on, and the other because I'm not sure which way to order things in the initialiser list):
Method 1 - Include a declaration for the default constructor in A:
class A
{
public:
A(Stuff *pStuff);
A(void){};
};
As far as I can tell by stepping through this solution, A(void) never actually gets called. Why does this keep the compiler happy?
Method 2 - Expand the initialiser list for AAA to explicitly call A(Stuff *pStuff).
AAA::AAA(Stuff *pStuff)
: A(pStuff), AA(pStuff)
{
...
}
If I adopt this solution, is this the right way to order the initialiser list? Does it matter which way the list is ordered?
__________________
Maybe you should put some shorts on or something, if you wanna keep fighting evil today.
Last edited by OzOz; 11-24-2007 at 10:16 PM..
Reason: Forgot to add public specifiers to AA and AAA.
|