University of Leeds

Classes

Introduction

The example below shows a simple C++ class used to represent a circle. Note how the class has both header and .cpp files. The header file also includes header guards.

Circle.h

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#ifndef CIRCLE_H
#define CIRCLE_H

#define PI 3.14159265

class Circle {
 public:
  // only accessors and mutators are public in this example
  void set_radius(float radius);
  float get_area();
 private:
  // member variables are private and set/get via accessor/mutator
  float _radius;
  float _area;
};

#endif

Circle.cpp

1
2
3
4
5
6
7
8
9
#include "Circle.h"

// mutator method to set radius
void Circle::set_radius(float radius) { _radius = radius; }
// accessor method to get area
float Circle::get_area() {
  _area = PI * _radius * _radius;
  return _area;
}

Member variables

The properties of the class (area and radius) are represented by private member variables of appropriate type. Note that we use an underscore preceding the member variable name to make it clear that they are class member variables. We usually make member variables private to prevent users of the class modifying them directly and possibly affecting behaviour of the class. This is a demonstration of the principle of encapsulation.

Accessor and mutator methods

To control how users interact with our classes, we use public accessor and mutator methods. An accessor method allows a user to read the value of a member variable. Their names are usually prefixed with get_ to make this clearer to the user. On the other hand, mutator methods allow users of the class to change the value of a member variable in a controlled manner. Their names are usually pre-fixed with set_ to make this behaviour clear. In this example, we can use the get_area() accessor method to get the area of the circle and the set_radius() mutator method to set the radius.

Example

The example below demonstrates how this class could be used.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#include <iostream>
#include "Circle.h"

int main() {
  Circle circle;
  circle.set_radius(0.5);
  float area = circle.get_area();
  std::cout << "The circle has an area of " << area << " m^2.\n";
  return 0;
}

We create a Circle object named 'circle'. Note how the class name begins with an uppercase letter, while the object name begins with a lowercase letter. This naming convention makes it easier to distinguish between classes and objects in our code.

We can then use the mutator method to set the radius and the accessor method to calculate the area. Running the example would cause the following output to appear in the terminal.

The circle has an area of 0.785398 m^2