Reputation: 1816
Let me first say this is a purely academic question, since what I want to do can be better accomplished with multiple layers of inheritance.
That said, I wonder if it's possible to override a virtual function with an existing function without writing a wrapper or adding any inheritance layers. Code:
int myfunc2() { return 2; }
class Parent {
public:
virtual int myfunc() { return 0; }
};
class Child1 : public Parent {
public:
int myfunc() override { return 1; }
};
class Child2 : public Parent {
public:
// There a way to do this?
// int myfunc() = myfunc2;
// instead of this?
int myfunc() { return myfunc2(); };
};
int main() {
Child2 baz;
return baz.myfunc();
}
I'd like to override myfunc
in the definition of Child2
by simply "forwarding" the declaration to the existing declaration of myfunc2
.
Is this, or something akin to it, possible?
Context: I've got a bunch of child classes, some of which have identical definitions of myfunc
, some of which do not. A better solution is to create an intermediate child class that defines the common myfunc
and have the pertinent children inherit from that instead.
Upvotes: 0
Views: 90
Reputation: 311088
There is a problem.
A non-static member function accepts one more implicit parameter: pointer to the object itself. While a stand-alone function does not have such a parameter, For example you may not use the keyword this
or member access syntax inside the definition of a stand alone function.
Upvotes: 0
Reputation: 206717
// There a way to do this? // int myfunc() = myfunc2; // instead of this? int myfunc() { return myfunc2(); };
No, there isn't.
Upvotes: 5