Page 1 of 1

Const Overloading

Posted: Thu Jun 07, 2012 12:49 am
by XianForce
When returning a pointer or reference to an object from a member method as such:

Code: Select all

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& :

Code: Select all

A const& GetA() const { return a; }
A& GetA() { return 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?

Re: Const Overloading

Posted: Thu Jun 07, 2012 10:46 am
by bbguimaraes
The problem with just a non-const accessor is this:

Code: Select all

void f(const B & b) {
    b.GetA();
}
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.

Re: Const Overloading

Posted: Thu Jun 07, 2012 4:11 pm
by XianForce
bbguimaraes wrote:The problem with just a non-const accessor is this:

Code: Select all

void f(const B & b) {
    b.GetA();
}
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.

So if I were to say:

Code: Select all

b.GetA();
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.

Re: Const Overloading

Posted: Fri Jun 08, 2012 11:36 am
by Falco Girgis
XianForce wrote:You mean without a non-const accessor .
No, he doesn't.
XianForce wrote:So if I were to say:

Code: Select all

b.GetA();
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.

Re: Const Overloading

Posted: Fri Jun 08, 2012 11:52 pm
by XianForce
Oh crap, I'm an idiot... Hahaha! Thank you guys :)!