HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Should this Point class remain a class, or become a struct?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thisstructpointremainshouldclassbecome

Problem

I am just beginning to dabble in C++. Would you implement this as a class like I did, or a struct? What are the pros and cons?

class Point
{
private:
    double _x;
    double _y;

public:
    Point();
    Point(double x, double y);
        ~Point();
        Point(Point& other);
        double GetX();
        void SetX(double x);
        double GetY();
        void SetY(double y);
};

Point::Point() : _x(0.0), _y(0.0)
{
}

Point::Point(double x, double y) : _x(x), _y(y)
{
}

Point::Point(Point& other) : _x(other._x), _y(other._y)
{
}

Point::~Point()
{
}

double Point::GetX()
{
    return _x;
}

void Point::SetX(double x)
{
    _x = x;
}

double Point::GetY()
{
    return _y;
}

void Point::SetY(double y)
{
    _y = y;
}

Solution

If you are using point as a property bag (like this).

Then just make it a struct (leave the members public). If you think there is a slight possibility of modifying the implementation then use get/set (ers) to access the memebrs but this class is so simple it seems over kill.

If this is part of a school class then your professor is going to say use member accessors so that the internal implementation can change and the internal implementation can change without the class interface being changed.

Though true in this simplistic case its just not going to happen.

Though I would add constructors to make sure the members are correctly initialized.

PS. Try not to use a leading underscore on identifiers. Though in this case it is not a problem the rules are non trivial and not well known so best avoided. see https://stackoverflow.com/a/228797/14065

Context

StackExchange Code Review Q#27156, answer score: 5

Revisions (0)

No revisions yet.