Can’t use function in inheritance using template [closed]

template <typename T1, typename T2>
class Parent {
protected:
    T1 _data1;
    T2 _data2;

public:
    Parent(T1 init_data1, T2 init_data2)
            : _data1(init_data1), _data2(init_data2)
    {
        std::cout << "Parent created" << std::endl;
    }

    virtual ~Parent()
    {
        std::cout << "Parent deleted" << std::endl;
    }

    virtual T2 multiple() = 0;
};

template <typename T1, typename T2>
class Child : public Parent<T1, T2> {
public:
    Child(T1 init_data1, T2 init_data2)
            : Parent<T1, T2>(init_data1, init_data2)
    {
        std::cout << "Child created" << std::endl;
    }

    ~Child()
    {
        std::cout << "Child deleted" << std::endl;
    }

    T1 get_data1() const { return this->_data1; }

    T2 get_data2() const { return this->_data2; }

    T2 multiple() override
    {
        //return Parent<T1, T2>::_data1 * Parent<T1, T2>::_data2; // Another option
        return this->_data1 * this->_data2;
    }
};

template <typename T1, typename T2>
std::ostream& operator<<(std::ostream& output, const Child<T1, T2>* child)
{
    output << child->get_data1() << ", "  << child->get_data2() << std::endl;
    return output;
}

int main(int argc, char* argv[])
{
    Parent<int, float>* child = new Child<int, float>(1, 4.5);
    float num = child->multiple();
    std::cout << num << "\n";
    std::cout << (Child<int, float>*)child << std::endl;
    delete child;
}

One little note for the next line:

std::cout << (Child<int, float>*)child << std::endl;

In this operator overloading, you are using Child class functions, and this pointer is Parent type, which is not including those functions (even not in virtual). If you try to use those function in your way, you won’t get the expected result. The way that I’ve been shown is one way to solve this problem, another way is to create those functions in Parent class, and create this operator overloading to Parent class too:

template ...
class Parent {
    ...
public:
    ...
    virtual T2 multiple()         = 0;
    virtual T1 get_data1() const  = 0;
    virtual T2 get_data2() const  = 0;

};

template <typename T1, typename T2>
std::ostream& operator<<(std::ostream& output, const Parent<T1, T2>* parent)
{
    output << parent->get_data1() << ", "  << parent->get_data2() << std::endl;
    return output;
}

int main(int argc, char* argv[])
{
    Parent<int, float>* child = new Child<int, float>(1, 4.5);
    ...
    std::cout << child;
    delete child;
}

Leave a Comment