class base{
public:
virtual void foo(){
std::cout << "base::foo was called" << std::endl;;
}
void bar(){
foo();
std::cout << "base::bar was called" << std::endl;;
}
};
class derived : public base {
public:
void foo() {
std::cout << "derived::foo was called" << std::endl;
}
};
int main() {
derived der;
der.bar();
// desired output = "base::foo was called" "base::bar was called"
// actual output = "derived::foo was called" "base::bar was called"
}
Am I missing something obvious here?
Why does the bar()
function when called on an object of derived class call the derived::foo
function, even though the function itself only exists in the base class.
When a member function in a derived class overrides a virtual member function in a base class like this, that means it entirely replaces the function definition for most purposes. So calling the function foo
on the object der
created in main
will usually use the Derived::foo
definition. This behavior is consistent whether the code calling foo
is in a member of Derived
, or a member of Base
, or neither class.
The two major exceptions are:
class_type::func_name
syntax to call the function, that disables the virtual function logic and just calls the function you named (after normal name lookup and overload resolution).So since you say you want the program to call base::foo
, change base::bar
like:
void bar() {
base::foo();
std::cout << "base::bar was called" << std::endl;
}