constructor

the syntax of constructor in some books is name(){............} and some define as name():{.........}.what is the right way of declaration and definition of construction .
Both are correct:

The colon specifies an "initialization list" (see http://www.cprogramming.com/tutorial/initialization-lists-c++.html)

The initialization list is an easy and efficient way to initialize a variable. In the following example, MyInt is being initialized to 3. This isn't the best example, because it could be done in the body just as easily. The two functions below are effectively the same although I think the first one is more effecient because it initializes the value instead of just setting the value which I heard is faster.
1
2
3
4
5
6
7
class Name
{
  int MyInt;
public:
  Name() : MyInt(3) {}
//Name() { MyInt = 3; }
}


Another place where this is useful required is when you have a member class who requires a specific constructor itself. In the following example, we have the Person class which contains a Name object. If we wait until we are well into the meat of the constructor, then the Name object has already been created with the default constructor (and MyInt is uninitialized). In order to call a specific constructor, we have to do it in the initialization list of the parent object's constructor.
1
2
3
4
5
6
7
8
9
10
11
12
13
class Name
{
  int MyInt;
public:
  Name(int _i) : MyInt(_i) {} // Initializes MyInt to _i
}

class Person
{
  Name MyName;
public:
  Person() : MyName( Name(3) ) {} // Calls the above constructor and initializes MyInt to 3
}


A work-around to the above method that is used to solve the above problem of calling member constructors is to use pointers instead. In this scenario, an initialization list is not required, but you have to use the pointer (->) syntax whenever calling members of that class.
1
2
3
4
5
6
class Person
{
  Name* MyName; // Creates a pointer only, it doesn't point to anything yet
public:
  Person() { MyName = new Name(3); } // No initialization list.  MyName is created in the meat of the constructor.
};
Last edited on
Topic archived. No new replies allowed.