Search code examples
c++initialization-list

why C++ Initialization list is before brace?


I want to know what's difference in the following two class.

example 1:

class A
{
string name;
public:
  A(const char* _name):name(_name){}
  void print(){cout<<"A's name:"<<name<<endl;}
};

example 2:

class A
{
string name;
public:
  A(const char* _name){name(_name);}
  void print(){cout<<"A's name:"<<name<<endl;}}

why the example 1 is passed and the last one is wrong? Thanks


Solution

  • That's just how the language is defined. The member initializers should be placed before the body of the constructor.