Jad
Jad

Reputation: 61

C++ constructor with one default parameter and one variable parameter

I'm writing this class constructor:

element(int f=0, int a)
{
    first = f;
    inc = a;
    current = first - inc;
}

The parameters are assigned to member variables in the body of the constructor. I've been asked to get the following calls in main() to work:

prog = new element(3,5);
prog = new element(5);

I cannot change the order of (3,5). As in within the constructor, f needs to be passed first, and a second. However, f needs to be initialized to 0 if no value is passed in, that way the second call keeps f at 0 and instead only initializes a to 5.

The issue with this is that I get an error if I place the parameters in this order within the constructor signature.

How do I solve this?

Upvotes: 1

Views: 2914

Answers (3)

Muhammet Ali Asan
Muhammet Ali Asan

Reputation: 1514

First of all, you cannot have a non-default argument after a default argument. Default arguments must be last in the function argument list. See Default arguments.

You can create an overload for the constructor:

element(int f, int a)
{
    first = f;
    inc = a;
    current = first - inc;
}

element(int a) : element(0,a)
{
}

Upvotes: 2

Abhishek Jaisingh
Abhishek Jaisingh

Reputation: 1730

You cannot have parameters with default values precede normal parameters without default values. So, you need to reorder the arguments in your constructor prototype:

element(int a, int f=0)
{
    first = f;
    inc = a;
    current = first - inc;
}

Another alternative is to define an overloaded constructor:

element(int f, int a)
{
    first = f;
    inc = a;
    current = first - inc;
}

element(int a)
{
    first = 0;
    inc = a;
    current = first - inc;
}

Upvotes: 3

Vlad from Moscow
Vlad from Moscow

Reputation: 310990

This declaration of the constructor is invalid:

element(int f=0, int a)
{
    first = f;
    inc = a;
    current = first - inc;
}

If a parameter has a default argument, all subsequent parameters are also required to have a default argument.

What you need is to declare two constructors, like for example:

element(int f, int a) : first( f ), inc( a )
{
    current = first - inc;
}

element(int a) : element( 0, a )
{
}

It is desirable to declare the second constructor as explicit to prevent implicit conversions from a single integer to the element type:

explicit element(int a) : element( 0, a )
{
}

Upvotes: 5

Related Questions