Questions about a virtual function in C ++

I am starting C ++, now I'm learning virtual functions. There are several questions that confuse me a lot.

eg:

class A { public: virtual void f() { //do something; } } class B: public A { public: virtual void f() { //do something; } } 
  • class A contains the virtual function f() , and class B inherits it. Inside class B , the f() function is also declared virtual, so does that mean f() in class B overloads f() in class A ? Does it provide classes that inherit B to overload f() ? Or does B define a new virtual function other than f() in class A ?

  • Virtual functions provide a way to overload. If B inherits A and does not declare f() as virtual , then can the class C that inherits B overloads f() and achieve polymorphism?

+6
source share
4 answers

inside class B, the function f () is also declared virtual, which means that it means f () in overloading class B f () in class A

No, it does not overload. He redefines. Also, the 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 the same name but with different parameters. In your case, the signature of the function f is the same in both classes, which means that it does not overload; the derived class basically redefines the definition of the base class f() .

+4
source

The virtual keyword allows you to redefine overload functions.

In addition, the virtual attribute is inherited, so the virtual keyword is optional for f() in class B

+2
source

When you declare a virtual function that you really tell the compiler, this is what you want the function to behave polymorphically. That is, from your example, if we have the following:

 A* foo = new B(); foo->f(); 

it will call function B "f", not function "f". To take it further, if we have C that inherits from B, as you said:

 class C : public B{} B* foo = new C(); foo->f(): 

it calls B "f". If you defined it in C, it would call method C.

To explain the different behavior of virtual and non-virtual, 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 f var->g(); //calls Foo g, it not virtual 

has the meaning?

+1
source

Since A :: f is virtual and B :: f has the same signature, they say that B :: f redefines A :: f.

It means:

 A * p = new B; p->f(); // invokes B::f 

EDIT: the following is simply incorrect (see comments):

Since B :: f is also virtual, then the child class B can override it again. If B: f was not virtual, then any method with the same signature in the child class would simply obscure it (that is, it would be a different method).

So, the behavior depends on the parent.

0
source

Source: https://habr.com/ru/post/887439/


All Articles