Reputation: 9
I have an abstract class A that returns a pointer of its type. Then I have a derived class B which implements the methods defined in class A. I want the methods defined in class B to return class B pointers. Any idea how to do that?
class A {
public:
virtual A* foo() {}
}
class B: public A {}
B *x = new B();
x->foo(); // This should return B*
Do I need to override foo in B to return B*? Is there some better way ?
Upvotes: 1
Views: 141
Reputation: 22354
I can think of 2 ways to achieve that:
foo
to be virtual)This can only be done if the return types are covariant, but if B inherits from A then B is covariant to A.
class A {
public:
virtual A* foo() { return new A; }
};
class B: public A {
public:
B* foo() override { return new B; }
};
You can provide child class as template parameter for the base class.
template <typename T>
class A {
public:
T* foo() { return new T; }
};
class B: public A<B> {
// only B* foo() exists
};
Upvotes: 5