Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling overridden function from the overriding function

Suppose I have virtual function foo() in class B, and I need slightly different behavior in one of B's derived classes, class D. Is it OK to create an overriding function D::foo(), and call B::foo() from there, after the special case treatment? Like this:

void D::foo() {   if (/*something*/)      // do something   else      B::foo(); } 

I am not asking whether that would work, I know it will. I want to know, whether it is right in terms of a good OOD.

like image 920
Igor Avatar asked May 13 '09 10:05

Igor


People also ask

How do you call an overridden function?

Access Overridden Function in C++ To access the overridden function of the base class, we use the scope resolution operator :: . We can also access the overridden function by using a pointer of the base class to point to an object of the derived class and then calling the function from that pointer.

What is overriding function in C++?

Function overriding in C++ is a feature that allows us to use a function in the child class that is already present in its parent class. The child class inherits all the data members, and the member functions present in the parent class.

How do you stop a function from overriding in C++?

In C++, there's no way to forbid it, it's just that by definition of "override", only virtual functions can be "overridden".

How scope resolution is used with overridden function?

Uses of the scope resolution Operator It defines the member function outside of the class using the scope resolution. It is used to access the static variable and static function of a class. The scope resolution operator is used to override function in the Inheritance.


2 Answers

This is perfectly good. In fact, the canonical way of performing some operations is calling the base class method, then do whatever (or the other way around). I am thinking of operator= here. Constructors usually work that way, too, even if this is a bit disguised in the initialization list.

like image 153
Gorpik Avatar answered Sep 22 '22 08:09

Gorpik


Yes, its totally ok as long as you are not violating the Liskov Substitution Principle.

like image 21
Alex Jenter Avatar answered Sep 20 '22 08:09

Alex Jenter