Classes and Objects in C++
Bundle data and behaviour into one neat package
- 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
privateandpublic(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.
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.