Emmett
Emmett

Reputation: 357

How to give a variable a default value if no argument is supplied to the constructor? C++

How do I make it so a default value is given to a variable if no argument is supplied to the constructor?

For example:

class A { 

A(int x, int y)

}

int main() { 
 A(4);
}

In that example I have not passed a value to y, how would I make it so y has a default value of 0 for example because no arguments where supplied?

Upvotes: 0

Views: 1221

Answers (3)

Qaz
Qaz

Reputation: 61920

Use default arguments, with the restriction that parameters can only have default values reading from right to left, so defaulting x without defaulting y is not an option:

A(int x, int y = 0) {}

Your other choice is to make an overload:

A(int x, int y) {}
A(int x) {/*use 0 instead of y*/}

The second can work particularly well with delegating constructors for more complex combinations:

A(int x, int y) {/*do main work*/}
A(int x) : A(x, 0) {/*this is run after the other constructor*/}

As soon as you do any of these, though, be aware that implicit conversions to your class are easier. Instead of the only possible {6, 10}, you've gained the possibility of passing 5 as an A. Think hard before allowing these implicit conversions, and until you know you want them, stick explicit in front of the constructor signature to disable them.

Upvotes: 4

Captain Obvlious
Captain Obvlious

Reputation: 20063

If you want to pass a default value to a parameter you can specify it in the constructor declaration.

class A
{ 
    A(int x, int y = 0)
    {
    }
};

int main()
{ 
    A(4);
}

Be careful when declaring default arguments for a constructor. Any constructor that can be called with a single argument can invoke an implicit conversion if it is not declared explicit.

A(int x = 0, int y = 0) // <-- can invoke implicit conversion
A(int x, int y = 0)     // <-- can invoke implicit conversion
A(int x, int y)         // <-- does NOT implicit conversion

To prevent implicit conversions from occuring declare the constructor as explicit

explicit A(int x = 0, int y = 0) // <-- No longer invokes implicit conversion
explicit A(int x, int y = 0)     // <-- No longer invokes conversion
A(int x, int y)                  // <-- does not require explicit keyword

Upvotes: 1

sethi
sethi

Reputation: 1889

You have to give default variable so the constructor becomes

A(int x=5, int y=4)

}

The default value of y becomes 4 and x has default of 5

Upvotes: 0

Related Questions