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.
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.
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.
In C++, there's no way to forbid it, it's just that by definition of "override", only virtual functions can be "overridden".
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.
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.
Yes, its totally ok as long as you are not violating the Liskov Substitution Principle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With