I plan to create an interface (rather a virtual base class in c++) with a method that takes an argument of the own type.
class Base {
public:
virtual void seriousMethod(const Base &arg) = 0;
}
The derived class should however take not an argument of the base class type but of the derived class type.
class Derived: public Base {
public:
virtual void seriousMethod(const Derived &arg) { /* ... */ }
}
How would I realize this? Would I have to template the base class (e.g. Base<Derived>
) or is there a cleaner solution?
Suppose, the same function is defined in both the derived class and the based class. Now if we call this function using the object of the derived class, the function of the derived class is executed. This is known as function overriding in C++. The function in derived class overrides the function in base class.
override (C# reference) An override method provides a new implementation of the method inherited from a base class. The method that is overridden by an override declaration is known as the overridden base method. An override method must have the same signature as the overridden base method.
Function overriding is a feature that allows us to have a same function in child class which is already present in the parent class. A child class inherits the data members and member functions of parent class, but when you want to override a functionality in the child class then you can use function overriding.
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.
You can't do this directly. Think about this case:
Base b;
Derived d;
Base& d_ref = d;
d_ref.seriousMethod(b); // What happens here?
At compile-time, the variable d_ref
has static type Base
, so according to the definition of Base
, it should be able to take b
as a parameter to seriousMethod
.
But at runtime, the dynamic type of d_ref
is Derived
, so it according to the definition of Derived
, it can't take b
as a parameter to seriousMethod
. It can't convert b
to Dervied
since it might be a straight Base
object (if Base
is not abstract), or it might be some other class derived from Base
that is not the same as Derived
.
You are correct in assuming that the only real way to go about this is the curiously-recurring template pattern, i.e. templating Base
and defining Dervied
as:
class Derived : public Base<Derived> { ... }
This removes the problem illustrated above, because each type derived from Base<T>
will have a distinct base class, and will not be related to one another through inheritance.
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