Thuta Learning
AdvancedProgrammingbeginner

Classes & Objects

Relax. We'll talk through this in plain words — no textbook voice.

A class is a blueprint that defines the structure of an object. An object is an actual instance built in memory based on a class. Inside a class, you can write attributes/data and methods/functions.

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

class Course {
  public:
    string title;
    int lessons;

    void showInfo() {
        cout << title << " has " << lessons << " lessons.";
    }
};

int main() {
    Course cppCourse;
    cppCourse.title = "C++ Foundation";
    cppCourse.lessons = 20;

    cppCourse.showInfo();
    return 0;
}

Course class has title, lessons attributes and a showInfo() method. A cppCourse object is created, and its members are accessed with the dot operator ..

You should see
C++ Foundation has 20 lessons.

Info

Starting class names with a capital letter is common convention. Naming objects in lower camelCase makes them easier to read.

Easy traps

  • Don't forget the semicolon ; at the end of a class definition — it's an easy thing to overlook when writing C++ classes.
Classes & Objects | Thuta Learning