I am trying to understand inheritance in C++ properly.
Firstly, is it ok to have a class that returns instantiations of itself?
class Class1 {
public:
Class1 foo();
}
Basically, I have a class that derives equations so it takes an equation and returns an equation.
If I wanted some subclasses of Class1 that also return instantiations of themselves:
class开发者_高级运维 Child : public Class1 {
public:
Child bar();
}
and I wanted to use some of the functions of Class1 but instead of returning Class1's, I would want to return Child objects, would this be possible with inheritance?
Thank you, hopefully this question isn't too dumb.
As written, there's no problem, but how do you intend to use it. Return
by value involves copy, and copy and polymorphism don't generally go
well together. Usually (but there are exceptions), it's preferable to
return a pointer to a newly allocated instance. (You'll have to address
memory management issues if you do this. If the logical meaning of the
class is such that cycles are impossible, then you can use
std::shared_ptr
; otherwise, you'll have to do something else.)
Yes,
It looks to me like you are described a well defined problem, known in Desing Pattern parlance, as a Factory
.
Consider the following:
class Class1 {
public:
static Class1 * getInstance( Equation * eq );
virtual void foo() = 0;
}
class Child : public Class1 {
public:
virtual void foo();
}
class OtherChild : public Class1 {
public:
virtual void foo();
}
You would implement the foo() method differently for both children.
So, for example, you could:
int main(){
Equation myEquation("x=y/4");
Class1 * myInstance = Class1::getInstance ( &myEquation );
myInstance->foo(); //would call the virtual method of the child class. You don't care what subclass, this was figured out by the "getInstance" method.
}
Firstly, is it ok to have a class that returns instantiations of itself?
Yes, it's OK, and in your case it sounds like a fine design. You can have the design that your proposed, or you can have a different design where your class will return a different object, e.g. class DerivedEquation
, or you can also have a class Deriver
which will take an Equation
and return anEquation
. All these designs are fine.
If I wanted some subclasses of Class1 that also return instantiations of themselves and I wanted to use some of the functions of Class1 but instead of returning Class1's, I would want to return Child objects, would this be possible with inheritance?
That's fine too. You can haveClass1::foo()
and Child::bar()
just as you proposed. Also, if you don't want to have 2 different function names, you can change the definition of foo
to Class1 * foo()
or Class1 & foo()
, and then you will be able to overload it in Child
.
精彩评论