why do we use VirtualFunction to allow derived class to use to base class function , yet we already have the inheritance acces s | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

why do we use VirtualFunction to allow derived class to use to base class function , yet we already have the inheritance acces s

hi all , In the Virtual Function C++ lesson , it is said :"As the attack() function is declared virtual, it works like a template, telling that the derived class might have an attack() function of its own." ok ! but why do we use VirtualFunction to allow derived class to use to base class function , yet we already have the inheritance access specifier :public which gives the possibility for the derived class to use the base class function ? It is two means to reach the same goal , Isn't it ?

23rd Aug 2018, 3:28 PM
S. Kaouche
S. Kaouche - avatar
2 Answers
0
S. Kaouche inheritance and virtual are used togather.... only virtual does not make sense... do one thing... have one function in base and child class... in main , create base class pointer pointing to child class and call function from base class pointer.. base* pb = new child; pb->function (); remove virtual keyword... observe which function (from derived or base) gets called with presence and absence of virtual keyword.. this is importance of virtual.. useful when pointer of base class point to derived class.. inheritance is necessary in this concept... now if inheritance alone is done, you can call base class function from derived class even if derived class does not have the same function redefined. virtual is used when you have function redefined in derived class and want to call the derived class function instead of base class function from pointer of base class which point to derive class.. feel free to ask for clarification..
23rd Aug 2018, 4:01 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Yes you're right ! "virtual is used when you ... want to call the derived class function instead of base class function from pointer " Thanks a lot !
23rd Aug 2018, 7:14 PM
S. Kaouche
S. Kaouche - avatar