C++, What does the colon after a constructor mean? [duplicate] - c++

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Variables After the Colon in a Constructor
C++ constructor syntax question (noob)
I have some C++ code here:
class demo
{
private:
unsigned char len, *dat;
public:
demo(unsigned char le = 5, unsigned char default) : len(le)
{
dat = new char[len];
for (int i = 0; i <= le; i++)
dat[i] = default;
}
void ~demo(void)
{
delete [] *dat;
}
};
class newdemo : public demo
{
private:
int *dat1;
public:
newdemo(void) : demo(0, 0)
{
*dat1 = 0;
return 0;
}
};
My question is, what are the : len(le) and : demo(0, 0) called?
Is it something to do with inheritance?

As others have said, it's an initialisation list. You can use it for two things:
Calling base class constructors
Initialising member variables before the body of the constructor executes.
For case #1, I assume you understand inheritance (if that's not the case, let me know in the comments). So you are simply calling the constructor of your base class.
For case #2, the question may be asked: "Why not just initialise it in the body of the constructor?" The importance of the initialisation lists is particularly evident for const members. For instance, take a look at this situation, where I want to initialise m_val based on the constructor parameter:
class Demo
{
Demo(int& val)
{
m_val = val;
}
private:
const int& m_val;
};
By the C++ specification, this is illegal. We cannot change the value of a const variable in the constructor, because it is marked as const. So you can use the initialisation list:
class Demo
{
Demo(int& val) : m_val(val)
{
}
private:
const int& m_val;
};
That is the only time that you can change a const member variable. And as Michael noted in the comments section, it is also the only way to initialise a reference that is a class member.
Outside of using it to initialise const member variables, it seems to have been generally accepted as "the way" of initialising variables, so it's clear to other programmers reading your code.

This is called an initialization list. It is for passing arguments to the constructor of a parent class. Here is a good link explaining it: Initialization Lists in C++

It's called an initialization list. It initializes members before the body of the constructor executes.

It's called an initialization list. An initializer list is how you pass arguments to your member variables' constructors and for passing arguments to the parent class's constructor.
If you use = to assign in the constructor body, first the default constructor is called, then the assignment operator is called. This is a bit wasteful, and sometimes there's no equivalent assignment operator.

It means that len is not set using the default constructor. while the demo class is being constructed. For instance:
class Demo{
int foo;
public:
Demo(){ foo = 1;}
};
Would first place a value in foo before setting it to 1. It's slightly faster and more efficient.

You are calling the constructor of its base class, demo.

Related

Constructor Initializer list vs initializing in constructor’s body [duplicate]

This question already has answers here:
Why should I prefer to use member initialization lists?
(9 answers)
Default member values best practice
(3 answers)
Closed 4 years ago.
I'm trying to understand the real difference between the following Classes.
class A
{
public:
A()
:width(500)
,height(300){};
int width;
int height;
};
class B
{
public:
B()
{
width = 500;
height = 300;
};
int width;
int height;
};
class C
{
public:
int width = 500;
int height = 300;
};
Which one do you think is the best way to initialize width and height variables in a class?
Should I stick to one way over the others?
This excerpt has been taken from "Inside the C++ Object Model" by Stanley B. Lippman.
You must use the member initialization list in the following cases in
order for your program to compile:
1. When initializing a reference member
2. When initializing a const member
3. When invoking a base or member class constructor with a set of arguments
4. A few efficiency cases. (Here the program is correct w/o member initialization list)
For points 1-3, member initialization list is a must.
For point 4, it is not compulsory.
For example(point 4), given :
class Word {
String _name;
int _cnt;
public:
// not wrong, just naive ...
Word() {
_name = 0;
_cnt = 0;
}
};
This implementation of the Word constructor initializes _name once, then overrides the initialization with an assignment, resulting in the creation and the destruction of a temporary String object.
A significantly more efficient implementation would have been coded:
// preferred implementation
Word::Word : _name( 0 )
{
_cnt = 0;
}
Due to this optimisation, a lot of people prefer member initialization list, as a default approach to write constructors.
// some insist on this coding style
Word::Word()
: _cnt( 0 ), _name( 0 )
{}
A reasonable question to ask at this point is, what actually happens to the member initialization list?
The compiler iterates over the initialization list, inserting the initializations in the proper order within the constructor prior to any explicit user code.
For example, the previous Word constructor is expanded as follows:
// Pseudo C++ Code
Word::Word( /* this pointer goes here */ )
{
_name.String::String( 0 );
_cnt = 0;
}
Note : The order in which the list entries are set down is determined
by the declaration order of the members within the class declaration,
not the order within the initialization list. In this case, _name is
declared before _cnt in Word and so is placed first.
So coming back to your question :
class B is fine(since you are using primitive datatypes).
class A will generate the same code as class B
As for class C, the default constructor is first called, and then initialization of width and height would happen. This method should be preferred when there are going to be more than 1 constructor, and for each constructor width and height need to be defaulted to your desired values.
However, since the advent of C++11, and use of {} as uniform initialization, a more recommended approach for writing class C would be :
class C
{
public:
int width {500};
int height {300};
};

Defining Function in c++ in different style [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Variables After the Colon in a Constructor
C++ constructor syntax question (noob)
I have some C++ code here:
class demo
{
private:
unsigned char len, *dat;
public:
demo(unsigned char le = 5, unsigned char default) : len(le)
{
dat = new char[len];
for (int i = 0; i <= le; i++)
dat[i] = default;
}
void ~demo(void)
{
delete [] *dat;
}
};
class newdemo : public demo
{
private:
int *dat1;
public:
newdemo(void) : demo(0, 0)
{
*dat1 = 0;
return 0;
}
};
My question is, what are the : len(le) and : demo(0, 0) called?
Is it something to do with inheritance?
As others have said, it's an initialisation list. You can use it for two things:
Calling base class constructors
Initialising member variables before the body of the constructor executes.
For case #1, I assume you understand inheritance (if that's not the case, let me know in the comments). So you are simply calling the constructor of your base class.
For case #2, the question may be asked: "Why not just initialise it in the body of the constructor?" The importance of the initialisation lists is particularly evident for const members. For instance, take a look at this situation, where I want to initialise m_val based on the constructor parameter:
class Demo
{
Demo(int& val)
{
m_val = val;
}
private:
const int& m_val;
};
By the C++ specification, this is illegal. We cannot change the value of a const variable in the constructor, because it is marked as const. So you can use the initialisation list:
class Demo
{
Demo(int& val) : m_val(val)
{
}
private:
const int& m_val;
};
That is the only time that you can change a const member variable. And as Michael noted in the comments section, it is also the only way to initialise a reference that is a class member.
Outside of using it to initialise const member variables, it seems to have been generally accepted as "the way" of initialising variables, so it's clear to other programmers reading your code.
This is called an initialization list. It is for passing arguments to the constructor of a parent class. Here is a good link explaining it: Initialization Lists in C++
It's called an initialization list. It initializes members before the body of the constructor executes.
It's called an initialization list. An initializer list is how you pass arguments to your member variables' constructors and for passing arguments to the parent class's constructor.
If you use = to assign in the constructor body, first the default constructor is called, then the assignment operator is called. This is a bit wasteful, and sometimes there's no equivalent assignment operator.
It means that len is not set using the default constructor. while the demo class is being constructed. For instance:
class Demo{
int foo;
public:
Demo(){ foo = 1;}
};
Would first place a value in foo before setting it to 1. It's slightly faster and more efficient.
You are calling the constructor of its base class, demo.

Explanation of C++ class constructor syntax? [duplicate]

This question already has answers here:
What is this weird colon-member (" : ") syntax in the constructor?
(14 answers)
Closed 5 years ago.
Reading through The C++ Programming Language, 4th Edition, there's a class defined like so
class Vector
{
private:
int sz;
double *a;
public:
Vector(int s) :elem{new double[s]}, sz{s} {}
}
I'm a bit confused on how this constructor syntax works. I believe Vector(int s) is creating a constructor function that takes one parameter s, and that it initializes elem and sz. But why is there a :? I thought functions bodies were surrounded by {}? And so what do the empty braces {} at the end serve?
: is called an initialiser list, which is used to quickly and concisely set values for the member variables when the constructor is called.
{} is the constructor's method body. Since the constructor is similar to a method, there has to be a body present for the code to compile. Since there is no need for any code in there, an empty body is used so the function does nothing.
This is initialization with Initializer List.
: is used to "initialize" the members of a class (this method is also called
member initialization list)
there is a major difference between using : and function body {}
initiallizer list : initialize the members of class, whereas ,constructor body {} assigns the value to the members of the class.
the difference may not seem very big but it is actually the only way to initialize the const data type and reference data type members (which can only be initialized during declaration )
So when you do this
class Test
{
const int i; const string str;
public:
Test(int x, string y):i{x},str{y};
}
This would work, but if you try to assign values to const int i and const string str by writing their code in the body of constructor, it would lead to a result
And so what do the empty braces {} at the end serve?
nothing it is just compulsory to put those braces (even if it is empty)
They can basically serve as a function when you create an object of the class inside the main function and pass it the required arguments.

Is there any difference while assigning value in ctor? [duplicate]

This question already has answers here:
In this specific case, is there a difference between using a member initializer list and assigning values in a constructor?
(12 answers)
Closed 7 years ago.
While I was working in c++ I see two type of ctor definition.. Is there any difference while assigning value? Does one of them has advantages or just writing style ?
1st ctor definition:
class X
{
public:
X(int val):val_(val){}
private:
int val_;
};
2nd ctor definition:
class X
{
public:
X(int val)
{
val_ = val;
}
private:
int val_;
};
Technically yes, although you can typically not observe any difference for built-in types like int.
The difference is that your first snippet copy-constructs val_ from val, while the second one default constructs val_ and then assigns val to it. As I said above, this usually only matters for more complex types whose constructors actually do work.
A simple example which demonstrates the difference would be
class X
{
public:
X(int val):val_(val){}
private:
const int val_;
};
which compiles vs.
class X
{
public:
X(int val)
{
val_ = val;
}
private:
const int val_;
};
which does not.
Yes there is a difference. In a constructor initializer list, the member variables are constructed, while the assignments in the constructor body is assignments to already constructed variables.
For the basic types like int or float it's no actual difference though.
In your example, there is no difference. Since your member is an int, the two statements have the same effect.
If your member variable was an object, the first form would be better, because it would simply call the constructor of the object class, while the second form would create an object by using the default constructor, then create another, store it into a temporary, call the destructor on the first object, copy the temporary into your member variable, call the destructor again on the second object.

What is the better way to define a construtor in C++?Initialization list or Initialization in Ctor Body? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Initializing in constructors, best practice?
Advantages of using initializer list?
I have the following two ways to define the constructor in the Point Class :
class Point
{
public :
Point(double X,double Y):x(X),y(Y){}
Private :
double x,y;
}
Another way :
class Point
{
public :
Point(double X,double Y)
{
x= X;
y = Y;
}
Private :
double x,y;
}
I want to know which one is better and why?Is there is the use of copy ctor in the first case?
Where each one is preferred?Can some explain with the example?
Rgds,
Softy
Use initializer lists when possible. Although in this particular case it makes no difference, you'll get in the habit.
For POD types, the members don't get initialized twice so performance-wise it's the same thing. non-POD types are initialized before entering the constructor body, so they'll be initialized twice if you don't do it in the initializer list but in the body of the c-tor.
const members and references must be initialized in the initializer list. Again, doesn't apply to your case.
The second version does an assignment to the data members, whereas the first initializes them to the given values. The first version is preferred here. Although it may make little difference in the case of doubles, there is no reason at all to prefer a construction that performs extra operations. If your data members were not doubles, but types that are expensive to construct, you would be paying the penalty of default constructing them, and then assigning a value to them.
Example:
struct ExpensiveToConstruct { .... };
struct Foo {
Foo() {
// here, x has already been default constructed
x = SomeValue; // this is an assignment to the already constructed x.
}
ExpensiveToConstruct x;
};
struct Bar {
Bar : x(SomeValue) {
// only the constructor has been called. No assignemt.
}
ExpensiveToConstruct x;
};
Better to use initialize list in your ctor. It would be more efficient. In your 2nd way, ctor will initialize member data twice, with default value 1st, and then invoke statement in ctor.
and more, for const or reference member, should be initialized by init lists, cannot be initialized in ctor.