Home > Software design >  Holder class (Having some objects references) compile error: 'Can not be referenced -- it is a
Holder class (Having some objects references) compile error: 'Can not be referenced -- it is a

Time:05-14

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.
}

CodePudding user response:

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
    
}

Working Demo

CodePudding user response:

References (MyA) should be bound to something and can't be empty, since you don't tell what it should bind to, the default constructor is ill formed.

prog.cc: In function 'int main()': prog.cc:23:12: error: use of deleted function 'Holder::Holder()' 23 | Holder holder; // Compiler error: the default constructor of "Holder" cannot be referenced -- it is a deleted function | ^~~~~~ prog.cc:14:7: note: 'Holder::Holder()' is implicitly deleted because the default definition would be ill-formed: 14 | class Holder

You need to add a constructor specifying how to initialized MyA

Holder(A &obj):MyA(obj){}

and then create holder objects

A testA;
Holder holder(testA);
  • Related