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’
The reason why is that what’s actually happening here is you’re using an implicit conversion from
inttoClassAin the initialization ofmember. In expanded form it is actually doing the followingThis means that the
ClassAinstance 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 typeClassAAdditionally it’s a good practice to put
explicitin front of theClassAconstructor to avoid the silent implicit conversion.