-
class constructor
Hi,
i got a class:
Code:
class base{
private:
int age;
public:
base(int);
};
The constructor can be:
method A:
Code:
base::base(int _age):age(_age){
}
method B:
Code:
base::base(int _age){
age=_age;
}
are both the methods correct? is it correct in c++ to use method B?
do clarify.
thanks
-
Yes, they are both correct. There is no difference between them
EDIT: See Initialization List in C++
-
Although it is true that in this case there is no real difference between the two since age is of a built-in type, the difference between appropriate construction and default construction + assignment for a member variable of class type may be significant. Furthermore, const and reference member variables, as well as those of types without a default constructor, must be initialised using the initialisation list.