Search code examples
c++classinheritance

derived class cannot call its own method?


#include <iostream>
#include "memory"

// base class
class base
{
public:
    void setVal(int val)
    {
        m_val = val;
    }

    int getVal()
    {
        std::cout << "val = " <<m_val<<std::endl;
        return m_val;
    }

    bool checkVal(int val)
    {
        return val>8?true : false;
    }
    
private:
    int m_val = 5;
};

// derived class
class derived1: public base
{
private:
};

// derived class
class derived2: public base
{
public:
    bool checkd2Val()
    {
        checkVal(9);
    }
private:
};


int main()
{
    std::unique_ptr<base> d1;
    d1 = std::make_unique<derived1>();

    std::unique_ptr<base> d2;
    d2 = std::make_unique<derived2>();

    d2->checkd2Val(7);

    return 0;
}

The compilor gives error that says: No member named "checkd2Val" in base. I am wondering how do we call checkd2Val in this case? Thanks!!


Solution

  • The error is correct. You are trying to call checkd2Val() using a base* pointer, and checkd2Val() does not exist in the base class.

    If you really need to call checkd2Val() with d2 then you need to type-cast it, eg:

    static_cast<derived2*>(d2.get())->checkd2Val(7);
    

    However, this will still fail, because derived2::checkd2Val() does not accept an input parameter but main() is passing in a value.

    You should consider instead to declare base::checkVal() as virtual and have derived2 override it, eg:

    #include <iostream>
    #include <memory>
    
    // base class
    class base
    {
    public:
        void setVal(int val)
        {
            m_val = val;
        }
    
        int getVal()
        {
            std::cout << "val = " <<m_val<<std::endl;
            return m_val;
        }
    
        virtual bool checkVal(int val)
        {
            return val > 8;
        }
        
    private:
        int m_val = 5;
    };
    
    // derived class
    class derived2: public base
    {
    public:
        bool checkVal(int val) override
        {
            return base::checkVal(9);
        }
    };
    
    int main()
    {
        std::unique_ptr<base> d2 = std::make_unique<derived2>();
        d2->checkVal(7);
    
        return 0;
    }