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 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){}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With