1

I was going through a piece of code as mentioned below and found that the method in child class is non-virtual, still the method is getting called by its base class pointer. Can anybody tell me the reason why....??

class Base {
    virtual void method() { std::cout << "from Base" << std::endl; }
public:
    virtual ~Base() { method(); }
    void baseMethod() { method(); }
};

class A : public Base {
    void method() { std::cout << "from A" << std::endl; }
public:
    ~A() { method(); }
};


int main(void) {
    Base* base = new A;
    base->baseMethod();     
    getchar();
    return 0;       
}

Output - from A

apb_developer
  • 321
  • 2
  • 9

1 Answers1

2

The method in the derived class which overrides the virtual method will be virtual too; it has nothing to with that the keyword virtual is used for it or not.

Then this function in the class Derived is also virtual (whether or not the keyword virtual is used in its declaration) and overrides Base::vf (whether or not the word override is used in its declaration).

songyuanyao
  • 169,198
  • 16
  • 310
  • 405