2

i am getting error during practicing inheritace in c++. I tried googling but I got confused. Anybody please help me.

    #include <iostream>

using namespace std;

class complex{
protected:
    int a;
    complex(int a){
        this->a=a;
    }
    virtual void showData()=0;
};

class display:private complex{
public:
    display(int a=0):complex(a){
    }
    void showData(){
        cout << a << endl;
    }
    display operator +(complex &c2){
        display c3=this->a+c2.a;
        return c3;
    }
};

int main()
{
    display c1=5, c2=7, c3;
    c3=c1+c2;
    c3.showData();
    return 0;
}

The error i am getting is:

In member function 'display display::operator+(complex&)':|
error: 'int complex::a' is protected|
error: within this context|
In function 'int main()':
error: 'complex' is an inaccessible base of 'display'|
||=== Build failed: 3 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Shobhit Tewari
  • 535
  • 5
  • 20
  • 3
    `std::complex` already exists, so [`using namespace std;`](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) might be a source of problems as well. – Yksisarvinen Oct 15 '19 at 14:04
  • 1
    `display` can access `protected` members of its own base. It can't access `protected` members of any instance of `complex`. – Peter Oct 15 '19 at 14:12

1 Answers1

4

A derived class can access only public or protected data members of its own sub-objects of base classes.

In this context

display operator +(complex &c2){
    display c3=this->a+c2.a;
    return c3;
}

the object c2 is not a sub-object of a derived class. So within the operator you may not access its protected data.

Change the operator the following way

display operator +( const display &c2){
    return this->a + c2.a;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335