yash vaidya
yash vaidya

Reputation: 9

Do I have to override every function in base class, if I want to change the return type of a function?

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

Answers (1)

Yksisarvinen
Yksisarvinen

Reputation: 22354

I can think of 2 ways to achieve that:

1. Overriding (requires 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; }
};

2. Curiously Recurring Template Pattern (CRTP)

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

Related Questions