0

Somewhere in a blog I saw this line:

class A{
    private:
       int x;
       
       A(int x=0): x{x} {cout<<"hello";}
};

can anyone please clear what this line means:

(int x=0) : x{x}

with the constructor.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • Read about default argument values and the constructor's initializer list in your favourite C++ book. – molbdnilo Dec 09 '21 at 13:02
  • 1
    i think it isnt mentioned in the dupe, the member initializer list is a place where shadowing does not happen. In `x{x}` there is no ambiguity and the first `x` denotes the member, while the second `x` denotes the constructor parameter, though it is important to understand that there are two `x` in your code – 463035818_is_not_an_ai Dec 09 '21 at 13:39
  • `int x=0` is a parameter named `x`, that if the callsite omits providing an argument the 0 is used at the callsite. (This convenience has the ramification of a tighter dependency between callsite and the implementation. May be inappropriate for larger projects and SDKs.) the `x{x}` initializes the member variable `x` with the parameter `x`; some consider this same-name practice a bad one or at least worth discouraging (it's not ambiguous in the language, but it may cause some misunderstanding by the maintainer). – Eljay Dec 09 '21 at 14:53

0 Answers0