Skip to content
AgileLogics
5 min read

Introduction to Classes & Objects

Prerequisites: Namespaces

A class groups data (members) and behavior (member functions) together — C's struct could only hold data.

Syntax

class Dog {
public:
    std::string name;

    void bark() {
        std::cout << name << " says Woof!" << std::endl;
    }
};

Example

Dog myDog;
myDog.name = "Rex";
myDog.bark();

Expected output

Rex says Woof!

Unlike Java, C++ objects can live directly on the stack (Dog myDog; — no new needed at all), which is central to the RAII pattern covered in Level 2.

Practice

Create a Cat class with a name member and a meow() method that prints "<name> says Meow!".

Show solution
class Cat {
public:
    std::string name;

    void meow() {
        std::cout << name << " says Meow!" << std::endl;
    }
};