class A;
class B
{
A a;
public:
A& GetA() { return a; }
};
//...
B.GetA();
I've always just returned the reference and left nothing const. That was until I read an article about using the const keyword in respect to pointers and references. I also read about const overloading, so now I have two versions of GetA(). One which returns A const& and one that returns A& :
So now when I call "GetA()", which is it calling? Does the compiler opt to use the const version unless you mutate the object? or does it opt to use the simple reference unless you specifically declare a reference to a constant object?
Without a const accessor, you can't do that, because you can't call a non-const method on a const object. So the version called depends on the const-ness of the object.
Without a const accessor, you can't do that, because you can't call a non-const method on a const object. So the version called depends on the const-ness of the object.
You mean without a non-const accessor . But yes, I understand that. My question is: Which does it OPT to call? Because a non-const can call both inspecting and mutating functions, while const can only call inspecting.
having both const and non-const accessors, would that call return the const or non-const version? I don't explicitly assign it to a const, but I also don't do any mutating with it.
having both const and non-const accessors, would that call return the const or non-const version? I don't explicitly assign it to a const, but I also don't do any mutating with it.
It will return the non-const version, because you are invoking the method via a non-const object.