C++ Classes and Objects

A class is a blueprint for creating your own data type, and an object is one real thing built from that blueprint. Classes let you bundle related data and behavior together, which is the heart of object-oriented programming in C++.

So far you have used built-in types like int, double, and string. A class lets you invent brand-new types that model things from the real world, such as a car, a bank account, or a student. You describe the type once, then create as many objects from it as you like.

Defining a Class

You create a class with the class keyword followed by a name and a pair of curly braces. Inside the braces you list the members: variables that hold data (called attributes) and functions that describe behavior (called methods). Class names usually start with a capital letter to make them easy to spot.

A simple class with attributes

#include <iostream>
#include <string>
using namespace std;

class Car {
  public:
    string brand;   // attribute
    string model;   // attribute
    int year;       // attribute
};

int main() {
  Car myCar;                // create an object
  myCar.brand = "Toyota";   // set attribute values
  myCar.model = "Corolla";
  myCar.year = 2024;

  cout << myCar.brand << " " << myCar.model << " (" << myCar.year << ")";
  return 0;
}

The public keyword means the members can be reached from outside the class. Once the object myCar exists, you use the dot operator (.) to read or change each attribute.

Note: A class definition ends with a semicolon after the closing brace. Forgetting that semicolon is one of the most common mistakes for beginners, so watch out for it.

Creating Multiple Objects

One class can produce many independent objects. Each object keeps its own copy of the attributes, so changing one object never affects another.

Two objects from one class

#include <iostream>
#include <string>
using namespace std;

class Student {
  public:
    string name;
    int score;
};

int main() {
  Student a;
  a.name = "Maya";
  a.score = 92;

  Student b;
  b.name = "Leo";
  b.score = 78;

  cout << a.name << ": " << a.score << endl;
  cout << b.name << ": " << b.score << endl;
  return 0;
}

Class vs Object

TermMeaningExample
ClassThe blueprint or templateCar
ObjectA concrete instance built from the classmyCar
AttributeA variable that stores an object's databrand, year
MethodA function that defines an object's behaviorstartEngine()

Exercise: C++ Classes and Objects

By default, members of a class declared with the class keyword are