Initialization Constructor

Hey Guys!
What's the best way to define a constructor?, which one of the below?
Is there anything wrong with any style ?, best practice?

1
2
3
4
5
6
7
8
9
class Person {
public:
	Person(string n, int a) :
	name(n), age(a) {}
	
private:
	string name;
	int age;
};


and

1
2
3
4
5
6
7
class Person {
public:
	Person(string n, int a) { name = n; age = a; }
private:
	string name;
	int age;
};
I've never seen a constructor designed like the first one before, so that's actually quite interesting. I'm also quite new to programming, so that's probably why. I think it's up to you how you design it, as long as it follows the 3 main features of object oriented design.
1
2
3
4
5
6
7
8
9
10
11
12
13
class Person
{
private:
	string name;
	int age;

public:
	Person(string n, int a) :
	   name {n},
           age {a}
        {
        }
};


1) The 1st approach posted by you is preferred.
2) I have formatted it in a way that I prefer above.
3) It is better to use universal initializers (with {}) rather than with parentheses ().
4) Personally, I prefer to list the private members before the public ones, though some people prefer the other way.
Consider this case

1
2
3
4
5
6
7
8
9
10
11
12
13
class Person
{
private:
	const int birthYear;
	std::string name;

public:
	Person(string n, int y) :
		name {n},
        	birthYear {y}
        {
        }
};


Some things to note:

Because the birthYear member is constant, it CANNOT be modified within the body of the constructor. It must be initialized in the initialization list.

An initialization list allows you to call a constructor on an object. Assignment inside the body requires the default constructor to be called, and then modification of the object (setter, assignment operator, etc.) within the constructor body. This is almost always inefficient. So, whenever possible, use an initialization list!

The items in the constructor list will be initialized in the order that they are declared in the class definition. So, birthYear will be initialized before name because its declaration was first (line 4 vs. line 5), irrespective of where it shows up in the initialization list (line 10 vs. line 9). A good compiler will warn you of this. It's a good idea to keep them in the same order so you don't get confused--it sometimes makes a difference what order members are initialized.
Registered users can post here. Sign in or register to post.