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 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. ...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With