tags:

views:

113

answers:

2
class arbit
    {
        int var;
        public:

        int method1();
        int method1() const;

    };

Why does g++ does not give warning while declaring the same function twice here ?

+15  A: 

Because one is const and the other is not. These are different overloads, with different signatures. One or the other gets called, depending on whether the object you call it on is const.

Example:

arbit x;
x.method1(); // calls the non-const version
arbit const &y = x;
y.method1(); // calls the const version

You should declare a method as const if it doesn't modify the (visible) state of the object. That allows you to hand out const arbit objects, and be certain¹ that someone won't accidentally modify them.

For example, you would make a function setValue non-const (because it modifies the object), but getValue would be const. So on a const object, you could call getValue but not setValue.


¹ When there's a will, there's a way, and it's called const_cast. But forget that I ever told you.

Thomas
Yup, C++ treats the const as an overload parameter
Digikata
Overloading on `const` can be very useful. For example, check out `operator[]` in `std::vector`.
Fred Larson
A const member function can be invoked for both const and and nonconst objects, whereas a nonconst member function can be invoked only for nonconst objects. Now how do i call the const version of method1 function here from a non constant object x. is it const_cast , which can do the desired operation for me ?
Amit
@Amit: In real life both overloads generally do exactly the same thing. There is no need to choose yourself which one to call. The overloads only exist to propagate constness correctly (if you have a const vector, `operator[]` gives you non-modifiable references, otherwise it gives modifiable references and it is up to you what you do with the reference).
UncleBens
Thanks everyone for the inputs
Amit
@Amit Like @Uncle says, if a function has both a const and non-const version, they better do the same logical thing or you're just in for a world of hurt. But if you truly want the const version, you need to make the object const, via: `arbit x; static_cast<const arbit`.
GMan
+3  A: 

You can also overload with volatile modifier and a combination of the two: const volatile

#include <iostream>
using namespace std;

class foo {
public:
    void bar()                { cout << "bar()" << endl; }
    void bar() const          { cout << "bar() const" << endl; }
    void bar() volatile       { cout << "bar() volatile" << endl; }
    void bar() const volatile { cout << "bar() const volatile" << endl; }
};

int main() {
    foo f;
    f.bar();

    foo const f_const;
    f_const.bar();

    foo volatile f_volatile;
    f_volatile.bar();

    foo const volatile f_const_volatile;
    f_const_volatile.bar();
}

That will output:

bar()
bar() const
bar() volatile
bar() const volatile
SilverSun