• 12
• 12
• 9
• 10
• 13

Why declare a constructor this way?

This topic is 3839 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

I am trying to understand why someone would define a constructor in the following way.
class GameBoard{
public:
GameBoard(unsigned int size = 10);
.
.
.

I mean, what would be the purpose of providing a parameter, size, if you are setting it in the declaration of the constructor? I saw this in an example that I am learning from, but they make no mention of it.

Share on other sites
It's a default value.

That means that you could call the contructor like GameBoard(5) and size would be 5, or GameBoard() and size would default to 10.

Share on other sites
These sorts of things are default values. This means you can use GameBoard() [which will result in the size being set to 10], or GameBoard(n) [which will result in size being set to n]. It's a means of saving some time for the person writing the constructor, while still providing a default constructor [it's like writing two constructors in one]

*edit* beaten to it again.

Share on other sites
Note that default values can be used with any kind of function, not just constructors.

Share on other sites
Quote:
 Original post by SiCraneNote that default values can be used with any kind of function, not just constructors.

Also they have to be at the end of your parameter list if I'm not mistaken. You couldn't do this:

void foo(int a = 5, int b);

or else you run into errors. You can also have multiple default parameters to make much more complex examples:

void bar(int a = 1, int b = 1, int c = 2, int d = 3, int e = 5);

so now, from that one function declaration, we can do any of the following:

bar(); //use all default values
bar(2); //set a manually, use other default values
bar(2, 4); //set a and b
bar(2, 4, 6); //set a, b, and c
bar(2, 4, 6, 8); //set a, b, c, and d
bar(2, 4, 6, 8, 10); //set all five values

You can see that you have to fill in parameters left to right. You couldn't say

bar(2, 5);

and expect it to use 2 for b and 5 for e. It would use 2 for a and 5 for b and then use the default values for the rest.