0

Here the object of derived class d cannot call the protected member function of the class base.

#include <iostream>

using namespace std;

class base
{
protected:
    int i,j;
    void setij(int a,int b)
    {
        i=a;
        j=b;
    }
    void showij()
    {
        cout<<i<<" "<<j<<endl;
    }
};

class derived : protected base
{
    int k;
public:
    void show()
    {
        base b;
        b.setij(10,20);
        b.showij();
    }

};

int main()
{
    base b;
    derived d;
    d.setij(3,4);
    d.showij();
    d.show();
    return 0;
}

I expect the output is 10 20, but the compiler is showing error.

L. F.
  • 19,445
  • 8
  • 48
  • 82

2 Answers2

1

You used protected inheritance. The problem is not that the derived cannot access protected methods of the base, but the problem is that you cannot access base methods from outside of derived.

If you don't know what protected inheritance means you can read eg here Difference between private, public, and protected inheritance

I doubt you wanted to use protected inheritance here (why would you?). Change it to public inheritance and your code should be fine:

class derived : public base ...

PS: The error message should have told you what is the actual problem (albeit in a cryptic way). Please next time include it in the question. If you cannot understand it, probably others will.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
0

There is a lot wrong with this code. Even if you change the inheritance of class derived from protected to public, the following problems still exist:

  1. In class derived, statements b.setij(10,20); and b.showij(); will still generate compiler errors. See Why can't a derived class call protected member function in this code? for a good explanation. The short explanation: a method can only call a protected method in a base class on the object for which it was originally invoked.

  2. Function main will not be able to call d.setij(3,4); or d.showij(); because these are protected methods in class base.

This should run:

#include <iostream>

using namespace std;

class base
{
protected:
    int i,j;
    void setij(int a,int b)
    {
        i=a;
        j=b;
    }
    void showij()
    {
        cout<<i<<" "<<j<<endl;
    }
};

class derived : public base
{
    int k;
public:
    void show()
    {
        this->setij(10,20);
        this->showij();
    }

};

int main()
{
    derived d;
    d.show();
    return 0;
}
Booboo
  • 38,656
  • 3
  • 37
  • 60