C ++ - const keyword in methods and overloading

for this 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;
}

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

I realized that this is a keyword const, but I don’t understand why the compiler chooses different overloaded functions.

If I delete the keyword const, everything works as expected, calling in both casesDerived::bar

+4
source share
3 answers

This is because you are not overriding the function bar (). You define a function string new in a derived class with a different signature.

const , const bar() . ( , , bar() , )

+2

, const , . , const , .

+3

++ 11 override specifier, . override, , .

bar(int) ( bar(double):

class Base {
public:
  ....
  virtual void bar(int) { cout << "Base::bar(int)" << endl; }
};

class Derived : public Base {
public:
  ...
  //This isn't an override, program is well formed
  void bar(int) const { cout << "Derived::bar(int)" << endl; }
};

bar Derived . const , - . , , .

override ', , .

class Base {
public:
  ....
  virtual void bar(int) { cout << "Base::bar(int)" << endl; }
};

class Derived : public Base {
public:
  ...
  //This isn't an override, program is ill-formed, diagnostic required
  void bar(int) const override { cout << "Derived::bar(int)" << endl; }
};

, - .

class Base {
public:
  ....
  virtual void bar(int) { cout << "Base::bar(int)" << endl; }
};

class Derived : public Base {
public:
  ...
  //This overrides
  void bar(int) override { cout << "Derived::bar(int)" << endl; }
};

, override , , .

+2

Source: https://habr.com/ru/post/1667115/


All Articles