3

Anyone can explain this weird bit in this line of code to me?

ClassA::ClassA(std::string aName) : name(aName)

Appearantly, this is the declaration of that class

class ClassA
{
public:
    std::string name;
    ClassA(std::string aName);
};

And the weird line of code appeared in its cpp file

ClassA::ClassA(std::string aName) : name(aName)

It's not polymorphism right? But then, what is it?

  • 11
    That's a member initializer list, nothing to do with polymorphism. It initializes the member `name` with the value `aName`. – Luchian Grigore May 03 '13 at 07:49
  • @user, perhaps you could pick up a "learn C++ in 24 hours" book and read chapter 1. Or better, check out http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – Nicholas Wilson May 03 '13 at 09:59

4 Answers4

6

This is a constructor with an initialization list:

 ClassA::ClassA(std::string aName) 
 : name(aName) // constructor initialization list
 {
   // ctor body. name is already initialized here
 }

It means data member name gets initialized with the value of aName.

It is orthogonal to polymorphism.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • so I could assume that it's equivalent to declaring 'name' as a data member in the class declaration right. but if that's the case, then what is the scope of that data member? private? – user2345939 May 03 '13 at 07:55
  • @user2345939 it is not equivalent. `name` has to be a data member (or a base class). You are initializing `name`. `private`, `public` or `protected` doesn't matter here, it could be either. – juanchopanza May 03 '13 at 07:58
  • no, this doesn't declare the member, it just initializes it. It still has to be declared in the class definition. – jalf May 03 '13 at 07:58
3

it's a member initializer. Member

std::string name;

will be initilized with aName
Using this allows to skip the default constructor of std::string, which would be used otherwise, so this removes some overhead. Another option would be

ClassA::ClassA(std::string aName)
{
  // name is fist constucted with default constructor
  name = aName;  // value is assigned with operator =
}

and this is generally slower, and should be avoided

spiritwolfform
  • 2,263
  • 15
  • 16
  • you are right. i just did a quick research on member initializer and found out that initializing data member inside the class is actually less efficient – user2345939 May 03 '13 at 08:13
0

It's just the initialisation list. When you specify the constructor you can initialise member variables in this list.

Nick
  • 25,026
  • 7
  • 51
  • 83
0

Its an initialization list, which is a neat and clear way of initializing member variables in C++

Community
  • 1
  • 1
John Sibly
  • 22,782
  • 7
  • 63
  • 80