user23
user23

Reputation: 425

Static member function cannot access protected member of class

My understanding is static member functions can access private, protected members of the class. Here in my code, sortPoint2DXAsc should be able to access X and Y since it's member function of Point2D. But I get this error:

Point2D.h: In function ‘bool sortPoint2DXAsc(const Point2D&, const Point2D&)’:
Point2D.h:22:7: error: ‘int Point2D::x’ is protected
Point2D.cpp:41:21: error: within this context
Point2D.h:22:7: error: ‘int Point2D::x’ is protected
Point2D.cpp:41:31: error: within this context
Point2D.h:22:7: error: ‘int Point2D::x’ is protected
Point2D.cpp:41:44: error: within this context
Point2D.h:22:7: error: ‘int Point2D::x’ is protected
Point2D.cpp:41:55: error: within this context
Point2D.h:23:7: error: ‘int Point2D::y’ is protected
Point2D.cpp:41:67: error: within this context
Point2D.h:23:7: error: ‘int Point2D::y’ is protected
Point2D.cpp:41:77: error: within this context

Here is my code:

class Point2D
{

    protected:  
        int x;
        int y;

    public:
        //Constructor
        Point2D();
        Point2D (int x, int y);

        //Accessors
        int getX();
        int getY();

        //Mutators
        void setX (int x);
        void setY (int y);

        static bool sortPoint2DXAsc (const Point2D& left, const Point2D& right);

};

bool sortPoint2DXAsc (const Point2D& left, const Point2D& right) 
{
    return (left.x < right.x) || ((left.x == right.x) && (left.y < right.y));
}

Upvotes: 2

Views: 2114

Answers (1)

Gabriel L.
Gabriel L.

Reputation: 5014

I think you want something like this code tested :

class Point2D {

protected:  
    int x;
    int y;

public:
    //Constructor
    Point2D();
    Point2D (int x, int y);

    //Accessors
    int getX() const {return x; }
    int getY() const {return y;}

    //Mutators
    void setX (int x) {/*Do something with x*/}
    void setY (int y) {/*Do something with y*/}

    static bool sortPoint2DXAsc(const Point2D& left, const Point2D& right);

};


bool Point2D::sortPoint2DXAsc (const Point2D& left, const Point2D& right) 
{
        return (left.getX() < right.getX()) || ((left.getX() == right.getX()) && (left.getY() < right.getY()));
}

You can use static since you're not using this in your function. For example, if you was using this->x instead of left.getX(), you would have received an error because your function is static.

Now, here's a second example where you can access x and y without accessors. Since you're inside your class definition, x and y are accessible from left and right which are instance of Point2D even if they are protected.

Upvotes: 2

Related Questions