Question

Is it possible to access a base class function which has the same signature as that of a derived class function using a derived class object?. here's a sample of what I'm stating below..

class base1 {
public:
    void test()
    {cout<<"base1"<<endl;};
};

class der1 : public base1 {
public:
    void test()
    {cout<<"der1"<<endl;};
};

int main() {
der1 obj;
obj.test(); // How can I access the base class 'test()' here??
return 0;
}
Was it helpful?

Solution

You need to fully qualify the method name as it conflicts with the inherited one.

Use obj.base1::test()

OTHER TIPS

You can't override a method in derived class if you didn't provide a virtual key word.

class base1
{
    public:
        void test()
        {
            cout << "base1" << endl;
        };
};

class der1 : public base1
{
    public:
        void test()
        {
            cout << "der1" << endl;
        };
};

int main()
{
    der1 obj;
    obj.test(); // How can I access the base class 'test()' here??
    return 0;
}

So the above code is wrong. You have to give:

virtual void test();

in your base class

You can use this:

((base)obj).test();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top