tags:

views:

217

answers:

3

Hi

I just came across the following source code of an constructor.

testProg::testProg() : CCProg()  
{  
m_UID = n_UID = 0;  
}

Normally, an constructor looks as follows according to my understanding:

testProg::testProg()    
{    
m_UID = n_UID = 0;    
}

So I am wondering what is the purpose of this CCProg(), would be great if someone could quickly tell me what is going on here. Thanks!

+16  A: 

It would seem that testProg inherits from CCProg, and the no-args constructor for CCProg is being called from the initialization list of the testProg constructor.

Given that it is the no-args constructor that is being called, the explicit call isn't actually required (it would be called implicity anyway). Therefore the main use of this syntax would be to call a parent constructor that does take arguments.

For example:

testProg::testProg(int days) : CCProg(days)  
{  
m_UID = n_UID = 0;  
}

Here, if the explicit call was left out, the no-args constructor would be called implicity if one were available, otherwise compilation would fail.

Note that it is also possible (though far less likely), that CCProg is the name of a member variable belonging to testProg - again, the explicit call to the no-args constructor is not required as it would be called implicity.

William
Correct. For the OP's benefit, these are called "constructor initialization lists" in C++ lingo.
oggy
+6  A: 

It's either an explicit call to the base class constructor, if the class looks like this:

class testProg : public CCProg

or (less likely) a call to initialise a member variable, if the class looks like this:

class testProg
{
    Something CCProg;
    // ...
RichieHindle
+1 for mentioning both possibilities
MSalters
+4  A: 

Either:

  • class testProg is derived from class CCProg, or
  • class testProg has an embedded object named CCProg

In both cases it is an explicit call to a constructor of CCProg, and because it is a parameter-less constructor that call is allowed but not strictly necessary.

However, if CCProg had a constructor with an int parameter, you would have to call it with something like

testProg::testProg() : CCProg(1) { }

This syntax allows you to select a constructor (in case CCProg has more than 1) and pass a value. Also note the order in which things happen: CCProg is constructed before the testprog ctor body is entered.

Henk Holterman