class arbit
{
int var;
public:
int method1();
int method1() const;
};
Why does g++ does not give warning while declaring the same function twice here ?
class arbit
{
int var;
public:
int method1();
int method1() const;
};
Why does g++ does not give warning while declaring the same function twice here ?
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.
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