Skip to main content

17.6) Simple Class Definition Example


A basic class definition for rectangular shapes could look like this:

class Rectangle
{
  public:
    Rectangle(int, int, int, int);
    int get_x();
    int get_y();
    int get_width();
    int get_height();
  private:
    int corner_x;
    int corner_y;
    int width;
    int height;
};

The private section indicates that a rectangle is characterised by four integer instance variables, representing the coordinates of one corner and its dimensions.

The public section specifies a constructor: a method with the same name as the class, with the job of initialising the instance variables of the class. The public section also specifies getter methods for the instance variables, allowing the outside world to see (but not modify) their values.