3

I'm learning OOP and it seems that I have encountered a problem.
CODE:

class line {
protected:
    double a;
public:

    line() {a = 1;}
    line(double var1) {a = var1;}
};

class rectangle: private line {
protected:
    double b;
public:
    double area() {return a * b;}

    rectangle():line() {b = 1;}
    rectangle(double var1):line(var1) {b = var1;}
    rectangle(double var1, double var2):line(var1) {b = var2;}
};

class parallelepiped: private rectangle{
private:
    double c;
public:
    double volume() {return area() * c;}
    void print() {  cout << "Parallelepiped rectangle information:" << endl;
                    cout << "a = " << a << ", b = " << b << ", c = " << c << endl;
                    cout << "Volume: " << volume() << endl << endl;}

    parallelepiped():rectangle() {c = 1;}
    parallelepiped(double var1):rectangle(var1) {c = var1;}
    parallelepiped(double var1, double var2):rectangle(var1) {c = var2;}
    parallelepiped(double var1, double var2, double var3):rectangle(var1, var2) {c = var3;}
};

Problem: error: 'double line::a' is protected within print().
Any way to print out 'a', and any general tips for learner?

Claudio
  • 10,614
  • 4
  • 31
  • 71
xTheEc0
  • 47
  • 7

3 Answers3

5

When learning OOP in C++ you don't need to use private inheritance. There are cases where private or protected inheritance are good design decisions but not when just starting out.

You should use public inheritance if you want to access members from superclasses

class rectangle: public line {};
class parallelepiped: public rectangle {};

Here's an SO explanation about the differences between private public and protected inheritance:

Difference between private, public, and protected inheritance

Community
  • 1
  • 1
Serve Laurijssen
  • 9,266
  • 5
  • 45
  • 98
  • 1
    Why should a rectangle be a sub-class of line? A rectangle is not a line. It is composed of lines, but that is composition and not inheritance. – Jens Mar 24 '16 at 12:07
2

In most of the cases there is no need of using private inheritance. Simply you want to use private inheritance when you want to hide to the user some methods that you have inherited from the other class.

Please find a very nice explanation here: When should I use C++ private inheritance?

As a beginner I am pretty sure you will not need this in a near future.

Community
  • 1
  • 1
Stefano
  • 3,981
  • 8
  • 36
  • 66
0

Private member, which is available in the current class and friend class, is unavailable in the derived calss.

It's ok to print out 'a', when class rectangle: private line is changed to class rectangle: public line.

Be careful to use private inheritance.