Classes and Objects

What is a class?

A class is a blueprint for making things. It describes what data something has (its attributes) and what it can do (its methods). An object is one real thing made from that blueprint.

Think of it like this: A class is like the design drawing for a car: it says every car has a colour and a speed, and can drive and brake. Each car built in the factory from that drawing is an object. You can build many cars from one drawing.

Your first class

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

class Dog {
public:
    string name;
    int age;

    void bark() {
        cout << name << " says: Woof!\n";
    }
};

int main() {
    Dog a;
    a.name = "Rex";
    a.age = 3;

    Dog b;
    b.name = "Bella";
    b.age = 5;

    a.bark();
    b.bark();
    return 0;
}

Output

Rex says: Woof!
Bella says: Woof!
  • class Dog { ... }; defines the blueprint. (Again, a semicolon at the end!)
  • public: means the members below can be used from outside the class. More on this soon.
  • Dog a; creates an object called a.
  • a.bark() calls the method on that object. Inside, name means this dog's name.

class vs struct

In C++, class and struct are almost the same. The only difference: in a struct members are public unless you say otherwise; in a class they are private unless you say otherwise.

Tip: A common habit: use struct for simple bundles of data, and class when the type has its own behaviour and rules.

HOME LABS COMMUNITY DASHBOARD