c++ - Calling overrided virtual function instead of overloaded -


say have part of code:

#include<iostream> using namespace std; class { public:     virtual int f(const a& other) const { return 1; } }; class b : public { public:     int f(const a& other) const { return 2; }     virtual int f(const b& other) const { return 3; } };  void go(const a& a, const a& a1, const b& b) {     cout << a1.f(a) << endl; //prints 2     cout << a1.f(a1) << endl; //prints 2     cout << a1.f(b) << endl; //prints 2 } int main() {     go(a(), b(), b());     system("pause");     return 0; } 

i can understand why first 2 print 2. cannot understand why last print 2. why doesn't prefers overloaded function in b?

i looked @ this , this couldn't manage understand these.

int b::f(const b& other) const doesn't override int a::f(const a& other) const because parameter type not same. won't called via calling f() on reference of base class a.

if member function vf declared virtual in class base, , class derived, derived, directly or indirectly, base, has declaration member function same

name parameter type list (but not return type) cv-qualifiers ref-qualifiers  

then function in class derived virtual (whether or not keyword virtual used in declaration) , overrides base::vf (whether or not word override used in declaration).

if use override specifier (since c++11) compiler generate error.

class b : public { public:     int f(const a& other) const { return 2; }     virtual int f(const b& other) const override { return 3; } }; 

such clang:

source_file.cpp:10:17: error: 'f' marked 'override' not override member functions     virtual int f(const b& other) const override { return 3; }                 ^ 

if add overload in base class, might want. note forward declaration of class b needed.

class b; class { public:     virtual int f(const a& other) const { return 1; }     virtual int f(const b& other) const { return 1; } }; 

live


Comments

Popular posts from this blog

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

windows - Debug iNetMgr.exe unhandle exception System.Management.Automation.CmdletInvocationException -

configurationsection - activeMq-5.13.3 setup configurations for wildfly 10.0.0 -