A class is a user-defined type that groups fields (member variables) and methods (member functions) together. Declare a class with the class keyword and end the definition with a semicolon:
class Circle {
public:
double radius;
};Object
An object is an instance of a class. Members of an object are accessed with the dot operator (.):
Circle c;
c.radius = 2.0;
std::cout << c.radius << "\n"; // 2Each object has its own copy of the fields:
Circle a;
Circle b;
a.radius = 1.0;
b.radius = 5.0; // a.radius is still 1.Method
Methods can be defined inside the class and use the fields of the object they are called on:
class Circle {
public:
double area() { return 3.14 * radius * radius; }
double radius;
};Methods can be defined outside the class using the scope resolution operator (::):
class Circle {
public:
double perimeter();
double radius;
};
double Circle::perimeter() {
return 2 * 3.14 * radius;
}Note
Members of a class are private by default so they must be listed under public: to be accessible outside the class.
Dan