musafir
musafir

Reputation: 29

C++ multiple constructor with different arguments

I have one ABC class whose constructor is taking 3 arguments e.g x1, x2 and l. One sample code is shown below. I am trying to make another constructor in the same class ABC that should take different arguments but, I am unable to do. It might be a very general question but I am unable to get satisfactory answers.

     class ABC {
      protected:
      X1& _x1;
      X2& _x2;
      Logger& _logger;
      ABC(X1& x1, X2& x2, Logger& l):_x1(x1), _x2(x2),_logger(l) {}
      ABC(X1& x1, Logger& l):_x1(x1),_logger(l) {} //getting error uninitialized reference member ‘ABC::_x2’
      ~ABC(){this->clear();}
      void clear(){}
      };

error uninitialized reference member ‘ABC::_x2'

Upvotes: 0

Views: 2724

Answers (4)

Werner Erasmus
Werner Erasmus

Reputation: 4076

A reference must be initialised. For class members, this means initialisation in the member initializer list of the constructor.

If the member may be remain uninitialized, make it a pointer and ensure that it is default initialized (ie :m2_() //null, where m2_ is M2* m2_;), or wrap it with a smart pointer that at least ensures default initialization

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726987

C++ requires you to initialize all reference members. If there are situations when a reference to an object is optional, it's best to replace a reference variable with a pointer:

X2* _x2;

If you must have a reference with a default, make a private static variable for it, and use that variable to initialize your reference variable:

class ABC {
private:
    static X2 _x2_default; // Declare it in a CPP file
protected:
    ...
    ABC(X1& x1, Logger& l):_x1(x1),_logger(l), _x2(_x2_default) {}
    ...
};

Upvotes: 1

Dietmar Kühl
Dietmar Kühl

Reputation: 154025

Well, thecompiler tells you what the problem is (and it is inrelated to having multiple constructors): your class has a reference member which is not initialized in the constructor: _x2. All reference members need to be initialized in the constructor.

Upvotes: 1

banach-space
banach-space

Reputation: 1821

The compiler is telling you the truth - you need to initialize the second reference in your class, i.e. _x2.

You cannot have uninitialized references so either don't use them or you need to initialize them in every constructor that you declare.

Upvotes: 1

Related Questions