In my C ++ program:
#include<iostream.h> class A { public: virtual void func() { cout<<"In A"<<endl; } }; class B:public A { public: void func() { cout<<"In B"<<endl; } }; class C:public B { public: void func() { cout<<"In C"<<endl; } }; int main() { B *ptr=new C; ptr->func(); }
operator must call B::func(). However, the function is called C::func(). Please shed some light on this. After deleting the virtual keyword in class "A" this does not happen anymore.
B::func()
C::func()
For the basics, you should read the C ++ FAQ Lite for virtual functions .
, . , , , , , , . , .
( , ). func() A, B C.
B:: func()
C, C.
C
, , , , , , , .
. , ptr C, , , B ( B *ptr, , C, C *ptr).
ptr
B
B *ptr
C *ptr
, B, , , , . C ( , , , func() ), .
func()
, , , B- .
:
B *obj = new B;
Then he would call B :: func ().To appreciate the functionality you expect, you should remove the new func implementation in C.If you use a virtual function, you actually say that I don’t know what type of object I have inside if it is from the same family of objects (in this A is the "father" of the "family"). All you know is that each member of the "family" must do other work for a specific part. For example:
class Father { public: virtual void func() { cout << "I do stuff"; } }; class Child : public Father { public: virtual void func() { cout << "I need to do something completely different"; } }; int main() { Father *f = new Father; f->func(); // output: I do stuff delete f; f = new Child; f->func(); // output: I need to do something completely different delete f; }
Source: https://habr.com/ru/post/1725256/More articles:Justification for the text - c #Можно ли сделать переход от F (Тип) к F без отражения и без словаря? - genericssouth. migrate entire database - djangoHow can I get gtk window window id - gtkUsing ModRewrite to get rid of extensions - url-rewritingRemoving "index.html" from url and adding "www" with one 301 redirect - redirectLINQ puts unnecessary trailing spaces on lines - sql-serverChange FocusVisualStyle throughout the application - stylesComplex flat files in SSIS - importIs anyone developing in the cloud? (Mostly using rdp to access your devenv) - visual-studioAll Articles