This question already has answers here:
What is this weird colon-member (" : ") syntax in the constructor?
(14 answers)
Closed 9 years ago.
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?
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.
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
It's just the initialisation list. When you specify the constructor you can initialise member variables in this list.
Its an initialization list, which is a neat and clear way of initializing member variables in C++
Related
This question already has answers here:
What is this weird colon-member (" : ") syntax in the constructor?
(14 answers)
Closed 2 years ago.
what does the : e(data) do in the following code? Why are the curly brackets { } empty in the folowing code? Also can constant members of a class be initialized in this way?
Is this kind of definition specific to a constructor or it can be applied to all functions in C++?
class binaryfile
{
private:
const entry &e;
public:
binaryfile(const entry &data) : e(data){}
ostream& write(ostream &o)
{
o<<e.b_write();
}
}
binaryfile(const entry &data) : e(data){}
Defines a constructor which takes one argument and initializes the member variable e to that argument's value. The braces are empty because the constructor does nothing more.
It's called a member initializer list and it only works in constructor(s).
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.
This question already has answers here:
When do we need to have a default constructor?
(7 answers)
Closed 8 years ago.
I have the following classes:
class ArithmeticExpression
{
public:
ArithmeticExpression(std::string expr);
}
class Command
{
public:
Command(){};
//this is a virtual class
}
class CommandAssign : public Command
{
private:
ArithmeticExpression expr;
public:
CommandAssign();
CommandAssign(ArithmeticExpression);
}
Now when I try to write the constructor for the CommandAssign class as in:
CommandAssign::CommandAssign(ArithmeticExpression expr)
:Command()
{
this -> expr = ArithmeticExpression(expr.getExpr());
}
I get the error:
no matching function for call to ‘ArithmeticExpression::ArithmeticExpression()’
:Command()
Apparently I can fix that by adding an empty constructor in ArithmeticExpression class that does not do anything. What is it so special about this empty constructor that makes it work? I do not explicitly call anywhere. Do you always need to define an empty constructor in C++?
I wanted to emphasize that although from the title it seems that my question is similar to the one some users suggested as being a duplicate of, the answer I was looking for is NOT there. I was simply trying to understand what happens when a constructor is called and how to avoid defining a useless default constructor, which I knew already is not automatically defined by the compiler in the case where I define one with parameters.
A default constructor will only be automatically generated by the compiler if no other constructors are defined.
EDIT:
The default constructor is needed for object initialization.
All members are initialised before the constructor body begins. If one doesn't have an entry in the initialiser list, then it will be default-initialised; but this is only possible (for a class type) if it has a default constructor.
expr is not initialised in the initialiser list, and doesn't have a default constructor (since declaring any constructor prevents one from being implicitly generated), so it can't be initialised - hence the error.
You should initialise it in the list, rather than reassigning it in the constructor body:
CommandAssign::CommandAssign(ArithmeticExpression expr) :
expr(expr.getExpr())
{}
Note that there's no need to explicitly default-construct the Command sub-object. This also requires the constructor of ArithmeticExpression to be public: it's private in your example code.
This question already has answers here:
Does a constructor / destructor have to have code, or is the function enough?
(3 answers)
Closed 9 years ago.
I have confusion regarding default and empty constructor. Does empty constructor also initializes class variable automatically ? Meaning if i use a empty constructor instead of default constructor , does that also initialize class member variable automatically ? For example, if use following code, does integer pointer is initialized to NULL ? Please confirm
// .h file
Class Test {
public:
Test();
~Test();
int *p;
}
// .cpp file
Test::Test()
{
// do something..
}
No, empty constructor is same as default constructor if you don't initialize any member variable inside it.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is this weird colon-member syntax in the constructor?
I'm trying to understand what this kind of code means
Say I have this
class OptionStudent: public Student // derived class from Student class
{
public:
explicit OptionStudent(const std::string id = "12345678",
const std::string first = "someone")
: Student(id, first)
{
count_++;
}
}
What is that colon after the "someone"): <-- part called or mean for this constructor?
I know the constructor may be a little incorrect but I don't know what this is called. I just copied my notes from what the instructor was writing on the board and didn't understand it.
Something to do with the class or object remembering something?
It is the member initialization list. In this case, it calls the base class's constructor with id and first as arguments. It could also provide initial values for non-static data members of your class (if you had any).
Note that the semicolon after Student(id, first); is a syntax error and needs to be removed.
It is called an "initialization list". See following article "Understanding Initialization Lists in C++".
The basic idea is that when you enter the code of constructor after { you should have all members initialized to values passed as arguments or default.
Using initialization lists you can also pass arguments directly to base class too! This is what is happening in example you are describing:
first, both id and first are set to some values using default parameter value.
second, these values are used to initialize base Student class.
Of course one can pass different values as OptionStudent arguments and these values would be used to initialize Student.