Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do overriding functions need to be specified virtual?

Tags:

c++

In Cplusplus, in a derived class, if we define a member function to override a member function in its parent class, do we need to declare the one in the derived class to be virtual?

For example, do we need to declare g to be virtual in B in order for it to override A::g? which one of the following is correct for the above purpose?

class A{
public:
void f(){printf("A");}
virtual void g(){printf("A");}
}
class B : public A{
public:
void f(){printf("B");}
void g(){printf("B");}
}

or

class A{
public:
void f(){printf("A");}
virtual void g(){printf("A");}
}
class B : public A{
public:
void f(){printf("B");}
virtual void g(){printf("B");}
}

Thanks.

like image 411
Tim Avatar asked Nov 28 '22 22:11

Tim


1 Answers

Once a method is virtual in a class, its child class has also these virtual class even if you don't add virtual to them.

Adding override is a good habit to avoid subtle error:

class A{
public:
    void f()         { printf("A"); }
    virtual void g() { printf("A"); }
};
class B : public A{
public:
   void f()          { printf("B"); }
   void g() override { printf("B"); }
};
like image 86
Jarod42 Avatar answered Dec 05 '22 18:12

Jarod42