Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Holder class (Having some objects references) compile error: 'Can not be referenced — it is a deletted funciton'

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
    
}

Working Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading