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
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.
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With