Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Must be initialized in constructor base/member? [duplicate]

I have this:

class SistemPornire
{
Motor& m;
Electromotor& e;
public:
SistemPornire(Motor&,Electromotor&);
}

where Motor and Electromotor are two other classes. I try to define the constructor for this class like this:

SistemPornire::SistemPornire(Motor& M,Electromotor& E)
{
this->m = M;
this->e = E;
}

but it gives me 'SistemPornire::m' : must be initialized in constructor base/member initializer list and 'SistemPornire::e' : must be initialized in constructor base/member initializer list

like image 352
user2116010 Avatar asked Mar 17 '13 13:03

user2116010


People also ask

What must be initialized in a constructor?

A class object with a constructor must be explicitly initialized or have a default constructor. Except for aggregate initialization, explicit initialization using a constructor is the only way to initialize non-static constant and reference class members.

Should a constructor initialize all members?

The safest approach is to initialise every variable at the point of construction. For class members, your constructors should ensure that every variable is initialised or that it has a default constructor of its own that does the same.

Does default constructor initialize members?

Default constructors are one of the special member functions. If no constructors are declared in a class, the compiler provides an implicit inline default constructor. If you rely on an implicit default constructor, be sure to initialize members in the class definition, as shown in the previous example.

How do you initialize a data member in a constructor?

Const member variables must be initialized. A member initialization list can also be used to initialize members that are classes. When variable b is constructed, the B(int) constructor is called with value 5. Before the body of the constructor executes, m_a is initialized, calling the A(int) constructor with value 4.


1 Answers

You have to use initialization lists, because references must always be initialized upon creation:

SistemPornire::SistemPornire(Motor& M,Electromotor& E) : m(M), e(E) { }
//                                                     ^^^^^^^^^^^^

If this wasn't required, the body of the constructor could access those references before they are bound to an object. In C++, however, references must always be bound to an object.

Initializations in an initializion list are always guaranteed to be performed before the body of the constructor is executed (and after the construction of all base class subobjects).

like image 105
Andy Prowl Avatar answered Oct 29 '22 04:10

Andy Prowl