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 ??
Once a function is declared virtual in a base class, it doesn’t matter if the
virtualkeyword 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: