Lesson 6 / 10

Object-Oriented Programming: Classes and Objects

class Course {npublic:n    Course(std::string title, int lessonCount) {n        this->title = title;n        this->lessonCount = lessonCount;n    }nn    std::string getTitle() {n        return title;n    }nnprivate:n    std::string title;n    int lessonCount;n};nnCourse cppCourse("C++", 10);nstd::cout << cppCourse.getTitle();   // C++

public vs private

Members listed under private can only be accessed from inside the class itself — outside code must go through public methods like getTitle(), protecting the object’s internal state from being set to something invalid. This is the same encapsulation principle you’d find in Java or Python, expressed with C++’s own syntax.

The constructor

The method with the same name as the class runs automatically whenever a new object is created — it’s where you set up starting values, exactly as in Java or Python. Unlike Python, C++ requires you to explicitly mark members public or private; class members default to private if you don’t specify (a struct, C++’s other similar keyword, defaults to public instead).

Destructors

class Course {npublic:n    ~Course() {n        std::cout << "Course object destroyed" << std::endl;n    }n};

A destructor (marked with ~) runs automatically when an object goes out of scope or is explicitly deleted — this is where C++ classes commonly release any resources they acquired, like memory, file handles, or network connections. Python and Java rely on garbage collection instead; C++ gives you this direct, predictable hook, which is part of why C++ programs can manage resources so precisely.

Multiple objects, independent state

Just as in Python and Java, each object created from a class has its own independent copy of that class’s member variables — changing one Course object’s title has no effect on any other Course object, even ones created from the exact same class.