c++ - Override function with "virtual" keyword and without it -


this question has answer here:

i'm reading virtual functions , little confused overriding virtual functions. want confirm below given codes same?

class a{ public:     virtual void fun(){ } }; class b :public a{ public:     void fun(){} }; 

and

class a{ public:     virtual void fun(){ } }; class b :public a{ public:     virtual void fun(){} }; 

if not same what's difference? expected b's function virtual keyword same b's derived. please clear confusion thanks.

yes, same. function overriding virtual function in base class implicitly declared virtual.

from last working draft of c++14 standard:

10.3 virtual functions [class.virtual]
if virtual member function vf declared in class base , in class derived, derived directly or indirectly base, member function vf same name, parameter-type-list (8.3.5), cv-qualification, , ref- § 10.3 249 c iso/iec n4296 qualifier (or absence of same) base::vf declared, derived::vf virtual (whether or not declared) , overrides(111) base::vf.

emphasis mine

as @mats , @ixsci pointed out, practice since c++11, use keyword override ensure overriding virtual function , not acidentally overloading function or overriding non-virtual function. personally, preferred style this, debate whether virtual keyword in b adds value or harming readability:

class a{ public:     virtual void fun(){ } };  class b :public a{ public:     virtual void fun() override {} }; 

Comments

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -