Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overriding virtual function with a non-virtual function

Tags:

c++

I have the header file "testcode.h"

#ifndef TESTCODE_H
#define TESTCODE_H

class A
{
public:
    A();
    ~A();
    virtual void Foo();

public:
    int mPublic;

protected:
    int mProtected;

private:
    int mPrivate;
};

class B : public A
{
public:
    B();
    ~B();
    void Foo();
};

#endif // TESTCODE_H

and a source file

#include "TestCode.h"

int main(int argc, char* argv[])
{
    A* b = new B();
    b->Foo();

    b->mPublic = 0;
    b->mProtected = 0;
    b->mPrivate = 0;

    delete b;

    return 0;
}

Here, i would like to know that when I am calling "b->Foo", the Foo function of the class B is called instead of class A. However, the Foo function of class B is not declared as virtual. Can anyone elaborate on this ??

like image 274
jerry Avatar asked Dec 21 '22 21:12

jerry


2 Answers

Once a function is declared virtual in a base class, it doesn't matter if the virtual keyword is used in the derived class's function. It will always be virtual in derived classes (whether or not it is so declared).

From the C++11 standard, 10.3.2:

If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name, parameter-type-list (8.3.5), cv-qualification, and refqualifier (or absence of same) as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides Base::vf. ...

like image 179
JohnPS Avatar answered Dec 24 '22 01:12

JohnPS


B::Foo doesn't need to be declared as virtual--the fact that A::Foo is virtual and B derives from A means it's virtual (and overridden). Check out the msdn article on the virtual functions for more info.

like image 25
SirPentor Avatar answered Dec 24 '22 01:12

SirPentor