Home > Back-end >  What is the meaning of: Base(int x): x{x}{}? [duplicate]
What is the meaning of: Base(int x): x{x}{}? [duplicate]

Time:10-03

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:

  1. the : after the corresponding constructor in the definition represents "Member Initialization".

  2. x is an integer

  3. C you are able to initialize primitive datatypes utilizing curly braces. See: https://www.educative.io/edpresso/declaring-a-variable-with-braces-in-cpp

  4. So therefore the x{x} is initializing x to the passed in value of the constructor.

  5. 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
}
  •  Tags:  
  • c
  • Related