I am a beginner of C++, I am studying virtual functions these days.
There are some questions confuse me a lot.
for example:
class A {
public:
virtual void f() {
//do something;
}
}
class B: public A {
public:
virtual void f() {
//do something;
}
}
-
class Acontains a virtual functionf(), andclass Binherits it. Insideclass B, the functionf()is also declared as virtual, so does this meanf()inclass Boverloadsf()inclass A? Does it allow classes which inheritBto overloadf()? Or doesBdefine a new virtual function which is different fromf()inclass A? -
Virtual functions provide a way of overloading methods. If
BinheritsAand does not declare thef()asvirtual, then can a classCwhich inheritsBoverload thef()and achieve polymorphism?
No, it doesn’t overload. It overrides. Also the keyword
virtualis optional in classB.B::f()will always be avirtualfunction, whether you writevirtualor not.The term overload is used when you define a function with same name but different parameter(s). In your case, the signature of the function
fis exactly same in both classes, that means it isn’t overloading; the derived class basically overrides the base class definition off().