简体   繁体   中英

accessing non-template base class virtual function from template derived class

I'm trying to understand the template and inheritance. I have a base class as follows:

class Base
{
public:
    virtual ~Base() {}
    virtual void setId(u_int8_t id)
    {
        m_id = id;
    }

private:
    u_int8_t m_id;
};

and a derived template class as follows:

template <typename T>
class Data : public Base
{
public:
    virtual void setId(u_int8_t id)
    {
        this->setId(id);
    }

    inline void setData(const T& data)
    {
        m_data = data;
    }

    inline T& data()
    {
        return m_data;
    }

private:
    T m_data;
};

this code compiles fine but crashes at run time. Why is this happening?

You get a stack overflow because setId keeps calling itself. To call the setId in the base class, use

virtual void setId(u_int8_t id)
{
    Base::setId(id);
}

This function:

virtual void setId(u_int8_t id)
{
    this->setId(id);
}

It is calling itself recursively, until the process runs out of stack space and you get a crash.

To call a function from the base-class you have to use the scope operator:

Base::setId(id);

The setId() function recursively calls itself forever. You want:

virtual void setId(u_int8_t id)
{
     Base::setId(Id);
}

You don't actually need setId(u_int8_t id) in Data . The method is inherited from Base . If you are intending to provide a different implementation in derived class, and use in this different implementation the implementation of the Base , then use Base::setId(id) (as Joachim Pileborg pointed out)

PS: Actually, there is nothing specific to templates in your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM