Skip to content

Introduction to OOP: Classes and Objects

Programming C++ Difficulty 1/5

Beginning of the lesson

Classes and Objects in C++

Bundle data and behaviour into one neat package

Big Idea: A class lets you group together the data something has and the behaviour it can do. From that single blueprint you can build as many objects as you like. This is the heart of Object-Oriented Programming (OOP).
By the end you will be able to:
  • explain the difference between a class and an object,
  • write a simple class with data and member functions,
  • create objects and use them with the dot (.),
  • protect data with private and public (encapsulation),
  • write a constructor that sets an object up.

1. A blueprint and the things it builds

Think of a class as a cookie cutter. The cutter is not a cookie you can eat — it only describes the shape. Each time you press it into the dough you get a real cookie: an object.

So a class is the plan, and an object is a real thing made from that plan. From one Dog class you can make many dog objects — Rex, Bella, and more — and each one keeps its own data.

One class, many objects. The class is written once; the objects are created whenever you need them.

2. Your first class: data + behaviour

A class holds two kinds of things: data (also called attributes or member variables) and behaviour (member functions, sometimes called methods). Here a Dog has a name and an age, and it can bark().

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

class Dog {
public:
    string name;          // data: an attribute
    int age;

    void bark() {         // behaviour: a member function
        cout << name << " says: Woof!" << endl;
    }
};

int main() {
    Dog d;                // create one object of type Dog
    d.name = "Rex";       // give its data some values
    d.age = 3;
    d.bark();             // call its behaviour
    return 0;
}

Expected output:

Rex says: Woof!

We create an object with Dog d;, reach its data with the dot operator (d.name), and call its behaviour with d.bark();. Notice the bark() function uses name directly — the data and the behaviour live together inside the class.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers