jeudi 6 août 2020

virtual function not accessible in derived class

The following code would not compile. GCC complains no matching function for call to ‘derived::print(std::__cxx11::string&).

class base
{
public:
    virtual void print(float x){}
    virtual void print(std::string str){}
};

template<class ProcessType>
class CProcess : public base
{
public:
    CProcess(ProcessType* process): m_Storage(process){}
    void print(float x) override{m_Storage->print(x);}
    void print(std::string str) override{m_Storage->print(str);}
private:
    ProcessType* m_Storage;
};

class derived: public base
{
public:
    void print(float x) override{}
    //void print(std::string str) override{}
};

base* ptr = new CProcess<derived>(new derived);
ptr->print(1.0f);

Class derived inherits print(std::string str) from base so why this error? Now if I also comment void print(float x) override{} in derived the compiler does not complain.

The final aim is to implement new behavior for print(float x) in derived but keeping the behavior of print(std::string str) from base.

I stripped down the production code to the smallest possible version to reproduce the issue so do not recommend smart pointers etc as they are in production code.

Aucun commentaire:

Enregistrer un commentaire