Search code examples
c++inheritancevirtual

calling a base function on a derived object


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.


Solution

  • 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:

    1. If you use a "qualified-id" 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;
    }
    
    1. During a constructor or destructor of the base class, the function from the base class (or one of its bases) will be called, ignoring overriders in the derived class(es). The object is considered to not yet or no longer be an object of the derived type. (And if the derived function were called and uses any derived members which are not yet created or already destroyed, this would be trouble.)