Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - const keyword in methods and overload

for which reason this program:

#include <iostream>
using namespace std;
class Base {
public:
  Base() { cout << "Costruttore Base" << endl; }
  virtual void foo(int) { cout << "Base::foo(int)" << endl; }
  virtual void bar(int) { cout << "Base::bar(int)" << endl; }
  virtual void bar(double) { cout << "Base::bar(double)" << endl; }
  virtual ~Base() { cout << "Distruttore Base" << endl; }
};
class Derived : public Base {
public:
  Derived() { cout << "Costruttore Derived" << endl; }
  void foo(int) { cout << "Derived::foo(int)" << endl; }
  void bar(int) const { cout << "Derived::bar(int)" << endl; }
  void bar(double) const { cout << "Derived::bar(double) const" << endl; }
  ~Derived() { cout << "Distruttore Derived" << endl; }
};
int main() {
  Derived derived;
  Base base;
  Base& base_ref = base;
  Base* base_ptr = &derived;
  Derived* derived_ptr = &derived;
  cout << "=== 1 ===" << endl;
  base_ptr->foo(12.0);
  base_ref.foo(7);
  base_ptr->bar(1.0);
  derived_ptr->bar(1.0);
  derived.bar(2);
  return 0;
}

In the call base_ptr->bar(1.0); is called Base::bar(double), instead in the derived_ptr->bar(1.0); is called Derived::bar(double) const.

I understood that is about the const keyword, but I don't understand why the compiler is choosing different overloaded functions.

If I remove the const keyword, everything is working as expected, calling in both cases the Derived::bar

like image 373
kopiro Avatar asked Mar 10 '23 03:03

kopiro


1 Answers

That's because const changes the signature of the function, so they're different. Either make both the base class and derived class const or not, otherwise one won't override the other.

like image 84
Paul Evans Avatar answered Mar 20 '23 12:03

Paul Evans