views:

98

answers:

3

Hi,

I have a constructor declaration as:

MyConstuctor(int inDenominator, int inNumerator);

and definition as

MyConstuctor::MyConstuctor(int inDenominator,
    int inNumerator, int inWholeNumber = 0)
{
    mNum = inNumerator;
    mDen = inDenominator;
    mWhole = inWholeNumber;
}

but i want to have an option of passing whole number as third parameter depending on caller object. is this the right way. if not what can be the alternative way.

A: 

No, you need to provide the default value in the declaration of the method only. The definition of the method should have all 3 parameters without the default value. If the user of the class chooses to pass the 3rd parameter it will be used, otherwise default value specified in the declaration will be used.

Naveen
+8  A: 

What you need is:

//declaration:
MyConstuctor(int inDenominator, int inNumerator, int inWholeNumber = 0); 

//definition:
MyConstuctor::MyConstuctor(int inDenominator,int inNumerator,int inWholeNumber) 
{   
    mNum = inNumerator;   
    mDen = inDenominator;   
    mWhole = inWholeNumber;   
}

This way you will be able to provide a non-default value for inWholeNumber; and you will be able not to provide it so 0 will be used as the default.


As an additional tip, better use initialization list in the definition:

//definition:
MyConstuctor::MyConstuctor(int inDenominator,int inNumerator,int inWholeNumber) :
    mNum(inNumerator), mDen(inDenominator), mWhole (inWholeNumber)
{   
}
Igor Oks
@Igor thanks for this tips.
iSight
A: 

You should add the default parameter to the declaration as well and the default value in the implementation is not necessary.

alopix
AFAIK, you can give the default in either place, but not more than once per argument (both in declaration and definition). For documentation purposes, it is recommended to give all defaults in the class definition (users of the class shouldn't need to look up the class implementation to see how it is used).
UncleBens