Why do you have to define an empty constructor c++ [duplicate] - c++

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.

Related

Do I have to define a default constructor for my class if I want to use "new" to allocate an array of it? [duplicate]

This question already has answers here:
Object array initialization without default constructor
(14 answers)
Closed 2 years ago.
Let's say I have a class A :
class A{
public:
A(int const& someValue, std::string const& anotherOne);
private:
std::string m_string_member;
int m_int_member;
};
And I want to allocate an array of this class using new :
A* myClassArray = new A[69];
I get the error : No default constructor available.
Do I have to write a default constructor for every class I want to use by calling new ?
Short answer: Yes.
Long answer: Lets start with this matrix here https://foonathan.net/images/special-member-functions.png. You provide a constructor which is not the default constructor (yours takes arguments). So the compiler won't automagically generate a default constructor for you. However, in your allocation, you ask the compiler to default construct 69 elements. How should the compiler do this? But, solving this issue is rather easy. Just provide the default constructor, or, even easier, use = default. The latter only works because all your members are default-constructible.
In c++ if no user-declared constructors of any kind are provided for a class type the compiler will always declare a default constructor. If you provide any constructor and want default constructor as well, you should define default constructor explicitly.

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.

Class default constructor [duplicate]

This question already has answers here:
Two constructors, which is default?
(6 answers)
Closed 8 years ago.
Assuming that we have the class TestClass in our C++ project. A default constructor is the one empty parameters list. So we have:
TestClass();
TestClass(int defaultParam = 0);
Can these two be considered default constructors? And if they can be, is it ethical to have a default constructor like the second line?
Either of
TestClass(void);
TestClass(int defaultParam=0);
can be used as the default constructor. When you have both, it is a problem since the compiler cannot distinguish between the two when the compiler needs to use a default constructor. E.g.
TestClass anObject;
TestClass objectArray[5];
Unrelated to your question
For stylistic reasons, you should use:
TestClass();
instead of
TestClass(void);
The second form is supported by C++ but it's not necessary. The argument type void is necessary only when declaring functions in C.
having more than 1 constructor is called constructor overloading. If there are two default constructors it will generate an error as the compiler will not know which constructor to call while creating the object. If you don't declare a default constructor the complier does it by itself.

does not have field named [duplicate]

This question already has answers here:
How can I initialize base class member variables in derived class constructor?
(7 answers)
Closed 4 years ago.
I have a mistake I cannot understand when initializing member data in an inherited class with two different methods I thought they should be theoretically identical.
class gSolObject
{
public:
gSolObject();
virtual ~gSolObject(){}
bool isCollisionObject;
};
class gPlanetObject : public gSolObject
{
public:
gPlanetObject();
~gPlanetObject(){};
};
gSolObject::gSolObject():isCollisionObject(1)
{
}
gPlanetObject::gPlanetObject():gSolObject(),isCollisionObject(0)
{
}
I get an error class 'gPlanetObject' does not have any field named 'isCollisionObject'.
However when I put the initialization right into the constructor's brackts {..} instead:
gPlanetObject::gPlanetObject():gSolObject()
{
isCollisionObject=0;
}
It compiles fine. Why would that be?
EDIT: This also does not work
gPlanetObject::gPlanetObject():gSolObject(),gSolObject::isCollisionObject(0)
It writes 'expected class-name before '(' token'
You can't initialize member variables declared in base classes, because the base class constructor has already initialized them. All base constructors execute before member constructors.
You can reassign it. Or you can call a base class constructor that takes an argument and initializes its members with that value.
Edited : You can't call a method of a uninitialized object (here gSolObject) and that's why it works when you execute isCollisionObject(0) in the constructor. Furthermore, if you always set it to 0, then you should use default value in the gSolObject constructor.

Initialization of Members in constructor [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C++ initialization lists
class Base
{
public:
int m_nValue;
Base(int nValue=0)
: m_nValue(nValue)
{
}
};
In this code, is the constructor initializing m_nvalue member variable?
I am not sure of this syntax:
Base(int nValue=0) : m_nValue(nValue) {}
We normally write it as:
Base(int nValue) { m_nValue = nValue;}
Can some one explain the above syntax of C++?
This syntax:
Base(int nValue=0)
: m_nValue(nValue)
is called the member initializer. It will initialize m_nValue with given nValue. This syntax is usually preferred in C++ since it is executed before the body of the constructor.
It's called member initializer list.
The member initializer list consists of a comma-separated list of initializers preceded by a colon. It’s placed after the closing
parenthesis of the argument list and before the opening bracket of the function body
Conceptually, these initializations
take place when the object is created and before any code within the brackets is executed.
Note:
You can’t use the member initializer list syntax with class methods other than constructors.
The way of initializing a variable in your code is called as member initializer list.
Generally we use such list to initialize const member variable (normal - non const also) we because at the time of construction we can give some value to const variable.
Second type of Initialization is basically a normal Parametrised constructor. That is used when you are having a object and at the time of creation of object you want to initialize the member variable.