questions about virtual function in c++
I am a beginner of C++, I am studying virtual func开发者_如何转开发tions 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 A
contains a virtual functionf()
, andclass B
inherits it. Insideclass B
, the functionf()
is also declared as virtual, so does this meanf()
inclass B
overloadsf()
inclass A
? Does it allow classes which inheritB
to overloadf()
? Or doesB
define a new virtual function which is different fromf()
inclass A
?Virtual functions provide a way of overloading methods. If
B
inheritsA
and does not declare thef()
asvirtual
, then can a classC
which inheritsB
overload thef()
and achieve polymorphism?
inside class B, the function f() also be declared as virtual, so does this mean f() in class B overload f() in class A
No, it doesn't overload. It overrides. Also the keyword virtual
is optional in class B
. B::f()
will always be a virtual
function, whether you write virtual
or 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 f
is exactly same in both classes, that means it isn't overloading; the derived class basically overrides the base class definition of f()
.
Virtual keyword allows you to override functions not overload them.
Also, the virtual attribute is inherited so virtual keyword is optional for f()
in class B
.
When you declare a function virtual what you are really saying to the compiler is that you want this function to behave in a polymorphic manner. That is, from your example if we have the following:
A* foo = new B();
foo->f();
it will call B's "f" function and not A's "f" function. To take it further, if we have a C which inherits from B like you've said:
class C : public B{}
B* foo = new C();
foo->f():
this calls B's "f". If you had defined it within C, it would have called C's method.
To explain the different behavior between virtual and non-virtual let's take this example:
struct Foo{
virtual void f();
void g();
};
struct Bar{
virtual void f();
void g();
};
Foo* var = new Bar();
var->f(); //calls Bar's f
var->g(); //calls Foo's g, it's not virtual
make sense?
Since A::f is virtual, and B::f has the same signature, it is said that B::f overrides A::f.
Which means:
A * p = new B;
p->f(); // invokes B::f
EDIT: The following is just plain wrong (see the comments):
Since B::f is also virtual, then it would be possible for a child class of B to override it again. If B:f wasn't virtual, than any method with the same signature in a child class would simply shadow it (that is, it would be a different method).
So, the behaviors depends on the parent.
精彩评论