-4

Visual studio is telling me I can't access a member variable from and instance of a parent class. Something like this:

class Point{
protected:
    int x, y;
};

class Quadrilateral : public Point
{
protected:
    Point A, B, C, D;
};

class Trapezoid : public Quadrilateral
{
public:
    bool isTrapezoid() {
        if (A.y == B.y && C.y == D.y)
            return true;
        return false;
    }
};

It's say that Point::y is not accessible through a pointer or object. Can anyone tell me why?

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Mai Phạm
  • 25
  • 1
  • 2

2 Answers2

2

Inheriting means you can access the protected member of the base class meaning in your case that Point::y can be used as Quadrilateral::y and Trapezoid::y inside the class, it doesn't mean that you can access y from any other Point object also not if they are members.
Inheriting from Point just to access A.y is wrong.
So Trapezoid can access A because of inheritance, but it can't access A.y because the accessibility of the members A has nothing to do with the inheritance in the question.

As Michael Walz commented, if you didn't want the members of Point to be public or accessible via member functions, you could declare Trapezoid as friend class of Point, which makes all members of Point accessible to Trapezoid. However, misusing this can lead to unexpected issues.

stefaanv
  • 14,072
  • 2
  • 31
  • 53
0

Point has protected members, no wonder they cannot be accessed. You should make them public.

Other points:

  • Quadrilateral shouldn't inherit from Point, as that does not make sense.
  • some syntax isn't real c++, you should fix it (e.g. class class, code inside parameter list of isTrapezoid.
  • make isTrapezoid to be a method that can be called on Quadrilateral, this should be a const method.
  • for simple classes like that perhaps you should make all your members public (depending on your code design).

class Point
{
public:
    int x, y;
};

class Quadrilateral
{
public:
    Point a, b, c, d;

    bool isTrapezoid() const
    {
        return a.y == b.y && c.y == d.y;
    }
};
Pavel P
  • 15,789
  • 11
  • 79
  • 128