Sign in to follow this  

Why declare a constructor this way?

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
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 this post


Link to post
Share on other sites
Quote:
Original post by SiCrane
Note 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.

Share this post


Link to post
Share on other sites

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

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this