I need a "holder" class. It is supposed to store objects references.
Like: holder.A = a; // Gets a reference!
Sample code bellow including the compiler error:
class A
{
};
class Holder
{
public:
A& MyA; // I want to store a reference.
};
int main()
{
A testA;
Holder holder; // Compiler error: the default constructor of "Holder" cannot be referenced -- it is a deleted function
holder.A = testA; // I was hopping to get testA reference.
}
>Solution :
The problem is that since your class Holder
has a reference data member MyA
, its default constructor Holder::Holder()
will be implicitly deleted.
This can be seen from Deleted implicitly-declared default constructor that says:
The implicitly-declared or defaulted (since C++11) default constructor for class T is undefined (until C++11)defined as deleted (since C++11) if any of the following is true:
T
has a member of reference type without a default initializer (since C++11).
(emphasis mine)
To solve this you can provide a constructor to initialize the reference data member MyA
as shown below:
class A
{
};
class Holder
{
public:
A& MyA;
//provide constructor that initialize the MyA in the constructor initializer list
Holder( A& a): MyA(a)//added this ctor
{
}
};
int main()
{
A testA;
Holder holder(testA); //pass testA
}