Pokee
Pokee

Reputation: 51

How do I get a variable inside a struct in a header file? C++

Basically one of my header files has been changed, and the function to return certain variables in it has been removed and I have no idea how to get the variables now. Can any please shed some light on the same.

The function getX() and getY() has been removed from the header file, and I am not allowed to add/modify the header file in any way. Is there a way I can still get the values of x and y from my main.cpp?:

struct Point
{
    int x;
    int y;

    Point ()                {   x = NULL;   y = NULL;   }
    Point (int x1, int y1)  {   x = x1;     y = y1;     }
    ~Point (void)           {   }


    Point & operator= (const Point &p)
    {   x = p.x;    y = p.y;    return (*this);     }

    bool operator== (const Point &p)
    {   return ( (x == p.x) && (y == p.y) );        } 

    bool operator!= (const Point &p)
    {   return ( (x != p.x) || (y != p.y) );        } 

    // 2 points are 'connected' but 'different' if they : 
    // i)  share the same 'x' but adjacent 'y' values, OR
    // ii) share the same 'y' but adjacent 'x' values!!
    bool isConnected (Point &p)
    {
        return (    ((x == p.x) && ( ((y-1) == p.y) || ((y+1) == p.y) )) || 
                    ((y == p.y) && ( ((x-1) == p.x) || ((x+1) == p.x) ))
               );
    }

    void display (std::ostream &outputStream=std::cout)     
    {   outputStream << "[" << x << ", " << y << "]";   }


    ============================================================
    // This two functions are now removed. =====================
    ============================================================
    int getX() // Removed.
    {
        return x;
    }

    int getY() // Removed.
    {
        return y;
    }

};

The part where I previously used these two functions:

int deadendX = pointOne.getX();
int deadendY = pointOne.getY();

So is there a way to do it now that the functions are removed from the header file? Like can I write some functions in my main.cpp to do this?

Upvotes: 0

Views: 119

Answers (2)

PeterK
PeterK

Reputation: 6317

This should do the trick:

int deadendX = pointOne.x;
int deadendY = pointOne.y;

x and y are public member variables of Point, so they are accessible to you.

Upvotes: 4

hyde
hyde

Reputation: 62797

You can access public struct/class members the same way, wether they are data members or methods. So just write this:

int deadendX = pointOne.x;
int deadendY = pointOne.y;

Upvotes: 3

Related Questions