I'm wondering if it is possible to derive functions from functions, similar to how classes can be derived from other classes? And if C++ does not explicitly allow this, is there a way to somehow indirectly derive functions from functions?
If you want foo()
to inherit some behavior from bar()
, you can simply make a call to bar()
inside foo()
.
No, you cannot use Generalization for functions. Inheritance is strictly a property of objects. You can use functional composition, however. This is C#, but you get the idea ...
class Comp
{
public void M1()
{
// do something
}
public void M2()
{
// do more stuff
M1(); // do something
}
}
I'm wondering if it is possible to derive functions from functions, similar to how classes can be derived from other classes?
Not possible.
And if C++ does not explicitly allow this, is there a way to somehow indirectly derive functions from functions?
How about this: in C++, you can create a kind of class which behaves like (and can be used) as a function, called a 'functor' or a 'function object'.
If you do, then you can define the operator()
of such a class as virtual, and define a subclass that overrides it.
A base class can have virtual member functions, which can be overridden in a derived class:
class Base
{
virtual void Foo();
};
class Derived : public Base
{
virtual void Foo(); // overrides
};
So in a way, the virtual functions in a base class are like "parameters", although they have default values. Translating "metaphorically" into functions, but keeping the names:
void Base(int foo = 10);
void Derived(int foo = 20)
{
Base(foo);
}
Here, the default parameter values play the role of the virtual function definitions.
So inheritance and virtual functions are just another form of parameterization, which is the fundamental notion in reusable programming.
I'm not certain that the question makes sense. What would a derived function look like? What would you achieve by deriving it?