View Single Post
Old 11-24-2007, 03:54 PM   #1 (permalink)
OzOz
Psycho
 
Location: Right here, right now.
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.
OzOz is offline  
 

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62