Change type of return

Asked

Viewed 86 times

0

How do I change the return type of a mother class function in the daughter 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, must be implicitly returned a value int.

2 answers

2

It does not, if the signature of the method is different then they are completely different and there is no inheritance between them unless the guy is covariant, which is not the case. If there will be inheritance you must respect the contract.

  • In c++ the return type is not part of the method signature. And yes, in some cases it is valid to have different signatures: https://stackoverflow.com/questions/4665117/c-virtual-function-return-type

  • If the signature is different, it will work?

  • @Felipenascimento within what you proposed, no, it is possible to completely change the way of doing everything, but there is no longer the problem you described in the question, it happens to be something else.

1

You can use the CRTP to solve the problem, only that 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 types of return are different

See working on Coliru

  • How did you put Mother<Child, int>, will only work for numbers?

  • @Felipenascimento As I said at the beginning, you have to know the types in compilation time, i.e., Mother<Child, int> has as son Child<int>, whereas Mother<Child, char> has as son Child<char>. Although it seems a limitation, in practice it is not due to the fact that most applications use them as interface functions, as you can see in the implementation of the function doit. Due to the system of template the function is instantiated for each type that is passed, made it transparent to types

Browser other questions tagged

You are not signed in. Login or sign up in order to post.