I was going through some tutorial online and found one c snippet which i am unable to figure out what exactly that snippet is doing. I need info like what this concept is called and why it is used.
Code is:
class Base{
int x;
public:
Base(){}
Base(int x): x{x}{} // this line i am unable to understand.
};
I want to know what this 5th line does and what is happening in compiler while compiling.
CodePudding user response:
Lets start off with the following:
the : after the corresponding constructor in the definition represents "Member Initialization".
x is an integer
C you are able to initialize primitive datatypes utilizing curly braces. See: https://www.educative.io/edpresso/declaring-a-variable-with-braces-in-cpp
So therefore the x{x} is initializing x to the passed in value of the constructor.
the last {} are for the constructor function call itself.
CodePudding user response:
It's this :
Base(int x) :
// initialization of members
x{ x } // aggregate initialization of member x with parameter x
// https://en.cppreference.com/w/cpp/language/aggregate_initialization
{
// empty function
}