Click here to Skip to main content
15,880,469 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I have this definition:
struct A
{
    int x;
    A(int x = 1): x(x) {} // user-defined default constructor
};


but not sure what is the benefit of doing x(x)?
furthermore, I want to understand what is the real meaning of this x(x) expression?

try to validate my understanding with gurus here.

What I have tried:

x(x) is to initialize a type int with value x.
Posted
Updated 29-May-21 9:58am
Comments
Richard MacCutchan 29-May-21 16:19pm    
It is just a shorthand way of saying this.x = x. As explained in the C++ documentation.
Southmountain 29-May-21 18:21pm    
thank you for this explanation!

1 solution

It says that if the constructor is called without an explicit argument, x defaults to 1. The constructor can then be called two ways:
C++
A one();
A two(2);
 
Share this answer
 
v2
Comments
Southmountain 29-May-21 16:39pm    
thank you! any link could you share for your statement?
Greg Utas 29-May-21 17:05pm    
https://en.cppreference.com/w/cpp/language/default_arguments

A great site that's my go-to for info on C++.
Southmountain 29-May-21 18:13pm    
thank you very much for this link! I like that site too.

I think I got this trick: one stone hits two birds:)
Greg Utas 29-May-21 17:14pm    
A couple of more points.

First, I hate the fact that "x" is used as a parameter name here, because it's also the name of A's field. There is undoubtedly a rule which says when "x" means the parameter and when it's short for this->x, but I don't know what it is because it is simply rude to do this kind of thing.

Second, defining a default can really be useful when there are rarely used trailing arguments. However, it is bad practice to define a default argument in a virtual/override/final function. The reason is that if different versions of the function specify different defaults, which one will be used is very confusing and error prone.
Southmountain 29-May-21 18:14pm    
thank you for sharing your understanding with me. now I am more confident to use this feature!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900