Change return type

0

How do I change the return type of a parent class function in the child class? For example:

class Mother {
  public:
    void Get() {}
};

template <typename Type>
class Child : public Mother {
  public:
    Type Get() {
        // TODO
    }
};

int main()
{
    Mother* m_ptr = new Child<int>();

    auto x = ((Child<>)m_ptr)->Get();
}

Thus, when accessing the function Get() of m_ptr , a value of int must be implicitly .

    
asked by anonymous 21.09.2017 / 03:14

2 answers

2

You can use CRTP to solve the problem, but the types have to be known at compile time. For example:

#include <iostream>

template <template <typename> class CLASS, typename T>
class Mother
{
public:
    T get() const { return static_cast<const CLASS<T>*>(this)->get();}
};

template <typename T>
class Child: public Mother<Child, T>
{
public:
    Child(T x) : v{x} {}
    T get() const {return v;}

    T v;
};

// Função criada só para mostrar a herança estática funcionando
template <template <typename> class CLASS, typename T>
T doit(const Mother<CLASS, T>& x)
{
    return x.get();
}

int main()
{
    auto f = Child<float>(6.6); // f é do tipo Child<float>
    auto c = Child<int>(5);      // c é do tipo Child<int>
    Mother<Child, int> m = c;   // m é do tipo Mother<Child, int>

    std::cout << doit(c) << std::endl;
    std::cout << doit(f) << std::endl;
}

Note that you can now call the function doit even if the return types are different

See working at Coliru

    
21.09.2017 / 04:18
1

Does not, if the method signature is different then they are completely different and there is no inheritance between them unless type is covariant , which is not the case. If there is inheritance, it must respect the contract.

    
21.09.2017 / 03:17