Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default constructor for a class with a reference data member?

I have a class MyClass in which I need to create a std::array of std::vector in the default constructor. However, this class has a data member which is a reference (of type Something) which also needs to be initialized in the constructor and I cannot do this in a default constructor.

How should I solve this?

class MyClass{
public:
    MyClass(); //Cannot instantiate s??
    MyClass(Something& s);
    Something& s;
}

MyClass array[10];   // MyClass needs a default constructor but a default 
                     // constructor won't be able to initialize s
like image 873
user997112 Avatar asked Feb 13 '23 07:02

user997112


1 Answers

A class with a reference member needs to set the reference in its constructors. In most cases this means, that the class cannot have a default constructor. The best way to solve the problem is use a pointer instead of a reference:

class MyClass{
public:
    MyClass() : s_(0) {}
    MyClass(Something* s) : s_(s) {}
    Something* s_;
}
like image 168
Danvil Avatar answered Feb 16 '23 02:02

Danvil