views:

343

answers:

5

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?

+16  A: 

If you want foo() to inherit some behavior from bar(), you can simply make a call to bar() inside foo().

Bastien Léonard
Or, as put more succinctly by Xzibit, "Yo Dawg." http://imgur.com/q5hnc.jpg
tgamblin
+8  A: 

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
    }
}
JP Alioto
+5  A: 

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.

ChrisW
Good answer. I'm not entirely sure, but I feel that there is a use for this... Somewhere...
Subtwo
Although i like operator() methods, i don't see how defining a subclass overriding previous operator() can help. Calling base operator() from derived object will be awkward : (*(Base*)this)();
Benoît
This seems slightly less awkward: Base::operator()()(or this->Base::operator()())
bk1e
+1  A: 

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.

Daniel Earwicker
+2  A: 

I'm not certain that the question makes sense. What would a derived function look like? What would you achieve by deriving it?

Michael J