I'm currently learning C++ and have come across the following problem: I have a templated interface BaseTemplate, which I would like to implement in a Child class without making the child a template itself. Sample code is as follows:
template <typename T>
class BaseTemplate
{
public:
virtual const T get() const = 0;
};
class Child : public BaseTemplate<int*>
{
public:
Child(int value) : myInt{value} {};
virtual const int* get() const override { return &myInt; };
private:
int myInt{0};
};
int main()
{
Child myChild = Child(10);
std::cout << myChild.get() << "\n";
return 0;
}
GCC produces the following error:
main.cpp|16|error: conflicting return type specified for ‘virtual const int* Child::get() const’
main.cpp|9|note: overridden function is ‘const T BaseTemplate<T>::get() const [with T = int*]’
I clearly understand that the error is related to
virtual const int* get() const override { return &myInt; }; but I don't understand what's the problem. If I change the return type (of course in both classes) to int, i. e. return a value instead of a pointer, it works fine. So what's wrong with pointers here?
Maybe it helps: in my actual code, I want return a pointer to a custom interface instead of int, the error there is related I believe
file_trees.h|19|error: invalid covariant return type for ‘virtual const IDirectoryNode* FileTree::DepthFirstIterator::getCurrent() const’
iterator_interface.h|10|note: overridden function is ‘const T IIterator<T>::getCurrent() const [with T = IDirectoryNode*]’