Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference Member Required to be Const?

In this simple example, why do I need to make 'member' const in order to get this to compile?

struct ClassA
{
    ClassA(int integer) {}
};

struct ClassB
{
    ClassB(int integer):
        member(integer)
    {
    }

    const ClassA& member;
};

int main()
{
    ClassB* b = new ClassB(12);

    return 0;
}

Otherwise, I get this error:

error: invalid initialization of reference of type 'ClassA&' from expression of type 'int'

like image 428
Dan Avatar asked Dec 09 '22 14:12

Dan


1 Answers

The reason why is that what's actually happening here is you're using an implicit conversion from int to ClassA in the initialization of member. In expanded form it is actually doing the following

member(ClassA(integer))

This means that the ClassA instance is a temporary. It's not legal to have a reference to a temporary variable only a const reference hence you get the compiler error.

The easiest fix is to remove the & modifier on member and make it just of type ClassA

ClassA member;

Additionally it's a good practice to put explicit in front of the ClassA constructor to avoid the silent implicit conversion.

explicit ClassA(int integer){}
like image 196
JaredPar Avatar answered Dec 12 '22 05:12

JaredPar