1

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.

Akhil Pathania
  • 542
  • 2
  • 5
  • 19
  • 2
    Usually online tutorials are bad for learning and waste of time. Invest your efforts for reading one of [The Definitive C++ Book Guide and List](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) written by professionals. – 273K Oct 02 '21 at 17:12
  • @S.M. That list could do with some updating by now ;) I think this is a good video though : "The best parts of C++" by jason turner. It at least explains a lot about references and the standard library : https://www.youtube.com/watch?v=iz5Qx18H6lg – Pepijn Kramer Oct 02 '21 at 17:18
  • @PepijnKramer The list is always actual. It is updated recently, edited on Jul 4 at 22:53. – 273K Oct 02 '21 at 17:20

2 Answers2

3

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
}
Pepijn Kramer
  • 9,356
  • 2
  • 8
  • 19
  • Nit. Should be `// aggregate initialization of member x with parameter x`. An **argument** is what is passed in at the callsite as the value to the **parameter**. (Mnemonic: an argument is to a parameter, as an automobile is to a parking spot.) – Eljay Oct 02 '21 at 17:12
  • Eljay yeah that's me knowing pretty much how it all works, not always spot on with the terminolgy. I'll keep working on it ;) – Pepijn Kramer Oct 02 '21 at 17:15
2

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.

Omid CompSCI
  • 1,861
  • 3
  • 17
  • 29
  • Your line 4 is incorrect. It is initializing `Base::x`, the member variable, to the value of `x` passed as the argument to the constructor. While they're both called `x`, in this context the compiler distinguishes between them. – Nathan Pierson Oct 02 '21 at 17:09
  • You're right its a constructor call with passed in argument. Will adjust. Hence why it's better to this->x = x. Or more meaningful names – Omid CompSCI Oct 02 '21 at 17:10
  • ...or different names. – Eljay Oct 02 '21 at 17:13