Lesson 132 +10 XP

Classes and Objects

Classes and Objects

In C++, a class bundles members - data and functions - under one name. From that class you create objects, and each object is a real set of data you can use.

Declaring a class

class Car {
public:
  string brand;
  string model;
  int year;
};
  • The keyword class opens the declarations.
  • The body sits between braces.
  • Ends with a semicolon after the closing brace - forget it and the compiler complains.

Creating an object

An object is declared like any other variable; the class name is the type:

Car myCar;   // an object of the Car class

myCar is now a real instance with room in memory for the attributes.

Accessing members

Use the dot operator to reach a member:

myCar.brand = "Toyota";
cout << myCar.brand;

The first line stores data into the object; the second line reads it back.

TL;DR

  • A class is defined with class + a name + braces + a semicolon.
  • An object is a variable whose type is the class: Car c;.
  • The dot operator . in reaches members of an object.
  • public: allows outside code to access the members that follow.