1

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?

3 Answers 3

6

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 )
{
}
Sign up to request clarification or add additional context in comments.

3 Comments

This is what I initially wanted to do, however the task implies I only should have one constructor. Do you think that's just a misstep on their part?
@Jad It is impossible with one constructor.
Thanks for the help.
3

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;
}

Comments

2

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)
{
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.