Thuta Learning
C++
AdvancedProgrammingBeginner

Classes & Objects

C++Lesson 1925 min

What you'll walk away with

  • Define a class with data members and member functions, then create several objects from it
  • Explain that each object owns its own data and that names inside a member function refer to the calling object through this
  • State how class and struct differ in default access
  • Write safer classes with default member initializers and const member functions

Explain it simply

Explain it simply

A class is like the blueprint for a house. The blueprint says how many rooms there are and how the doors open, but nobody can live inside a sheet of paper. An object is a house actually built from that blueprint: it takes up space in memory and holds its own data.

Just as one blueprint can produce many houses, one class can produce many objects. Inside the class you write two things together: the data each object must remember (data members) and the functions that work on that data (member functions). That keeps the data and the code that handles it in one place.

Problem → Why → Solution

The problem: related variables scattered everywhere

Let's store the name and lesson count of two courses without a class. Each course needs two separate variables, and every time you call a function you have to pick the matching pair by hand. The code below compiles and runs, yet it reports the C++ lesson count for the Python course.

courses.cpp
#include <iostream>
#include <string>

void showInfo(std::string title, int lessons) {
    std::cout << title << " has " << lessons << " lessons.\n";
}

int main() {
    std::string title1 = "C++ Foundation";
    int lessons1 = 20;
    std::string title2 = "Python Basics";
    int lessons2 = 12;

    showInfo(title1, lessons1);
    showInfo(title2, lessons1);   // wrong pair: nothing stops this
}

Why is this bug so easy to make?

To the compiler, title2 and lessons1 are just two unrelated variables; it has no idea they are supposed to belong together. With ten courses and five fields each you would juggle fifty variables, and the chance of a mismatched pair grows. A class ties those fields into one object, so a call like course.showInfo() always works on the right data.

Core concept: a class is a new type, an object is a value of it

Writing class Course { ... }; adds a brand-new type to the program, in the same family as int and std::string. The definition itself occupies no memory. Only when you write Course cppCourse; does an object come into existence, with room for one std::string and one int. Do not forget the semicolon after the closing brace: a class definition is a declaration, so it must end with ;.

A class holds two kinds of members. Data members such as title and lessons are each object's state, and every object gets its own copy. Member functions such as showInfo are behavior: their code is shared by all objects rather than duplicated inside each one. When you call cppCourse.showInfo(), the compiler passes a hidden pointer named this set to &cppCourse, so the plain name title inside the function means this->title, the title of cppCourse.

Member kindRepresentsPer object
Data member (title)The object's stateIts own separate copy
Member function (showInfo)What the object can doOne shared copy of the code

In C++, class and struct are almost the same thing. The only language difference is default access: members of a class are private unless you add a label, while members of a struct are public (the same default applies to base classes). A struct may still have member functions and constructors. By convention, people use struct for a plain bundle of data with no rules and class for a type that has rules to protect, called invariants.

If a built-in member such as int or double has no initializer, creating an object with Course c; leaves it holding an indeterminate value, and reading that garbage is undefined behavior. The cure is a default member initializer such as int lessons = 0;. Then every object starts life with a meaningful value, however it is created.

Mental model: one blueprint, many objects
  1. Class describes the shape of a type
  2. Each object gets its own data
  3. obj.f() passes this = &obj
  4. Member names in f() mean obj's members

Data lives separately in every object; member function code is shared by all of them.

General pattern

cpp
class ClassName {
public:
    Type dataMember = initialValue;          // state, one copy per object

    ReturnType memberFunction(Param p) const { // behavior, shared code
        return /* something using dataMember */;
    }
};                                           // the semicolon is required

ClassName objectName;                        // create an object
objectName.memberFunction(argument);         // call a member with .

Members after the public: label can be used from outside the class. Give data members a default value, and mark member functions that do not change the object as const. Once an object exists, objectName.member reaches both its data and its functions.

Example: a Course class and one object

This example defines the Course type and creates one object named cppCourse inside main(). The fields are filled in with the dot operator, then showInfo() is called. Watch which object's data the function reads.

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;
}

Code breakdown

  1. Line 5class Course {

    Starts the definition of a new type called Course. Nothing appears in memory because of this line; it is only the blueprint.

  2. Line 6public:

    Members after this label may be used from main(). A class defaults to private, so without this line cppCourse.title would be a compile error.

  3. Line 8int lessons;

    With no initializer, lessons holds an indeterminate value until main() assigns 20. Writing int lessons = 0; would make the class safer.

  4. Line 10void showInfo() {

    A member function. Inside it, title and lessons mean this->title and this->lessons, the data of whichever object it was called on. It changes nothing, so void showInfo() const would be even better.

  5. Line 16Course cppCourse;

    This is where an object really comes into being. title is constructed as an empty string; lessons is not set yet.

  6. Line 20cppCourse.showInfo();

    Calls the member function with the dot operator. For this call this is &cppCourse, so it prints "C++ Foundation has 20 lessons.".

You should see
C++ Foundation has 20 lessons.

Every object owns its own data

The program below creates Course objects and copies one into another. Assigning an object copies every data member, so changing the copy's lessons does not touch the object it came from. Thanks to the default member initializer, the draft object also starts safely at 0 lessons.

objects.cpp
#include <iostream>
#include <string>

class Course {
public:
    std::string title = "Untitled";
    int lessons = 0;

    void showInfo() const {
        std::cout << title << " has " << lessons << " lessons.\n";
    }
};

int main() {
    Course draft;                 // uses the default member initializers
    Course cpp;
    cpp.title = "C++ Foundation";
    cpp.lessons = 20;

    Course copy = cpp;            // copies title and lessons
    copy.lessons = 35;            // changes only the copy

    draft.showInfo();
    cpp.showInfo();
    copy.showInfo();
}

It prints "Untitled has 0 lessons.", "C++ Foundation has 20 lessons." and "C++ Foundation has 35 lessons.". Notice that cpp keeps its 20: the two objects occupy two separate places in memory.

const member functions and passing objects by reference

Objects are usually passed to functions as const references (const Course&) to avoid copying them. On a const object, though, you may only call member functions marked const. That const is a promise that the function does not modify the object, and the compiler rejects any attempt to change a member inside it.

const_members.cpp
#include <iostream>
#include <string>

class Course {
public:
    std::string title = "Untitled";
    int lessons = 0;

    bool isLong() const { return lessons > 15; }   // reads only
    void addLesson() { ++lessons; }                // modifies the object
};

void report(const Course& c) {                     // no copy is made
    std::cout << c.title << (c.isLong() ? ": long course\n" : ": short course\n");
    // c.addLesson();  would not compile: c is const
}

int main() {
    Course rust;
    rust.title = "Rust Basics";
    rust.lessons = 15;
    report(rust);
    rust.addLesson();
    report(rust);
}

The first report() prints "Rust Basics: short course"; addLesson() raises lessons to 16, so the second prints "Rust Basics: long course". Without const on isLong(), the call c.isLong() inside report() would not compile.

In real projects

Where this shows up in real projects

You have been using classes since the first lesson. std::string and std::vector are classes from the standard library, and name.size() or scores.push_back(90) are member function calls. Writing your own class means building types for your own domain that are as easy to use as those library types: a Player in a game, an Order in a shop, an HttpRequest in a server.

In larger projects the class definition goes in a header file (course.h) and the member function bodies go in a source file (course.cpp), written as void Course::showInfo() const { ... }. The :: (scope resolution) operator tells the compiler this is Course's showInfo. With that split, files that use the class include only the header, and changing an implementation detail does not force everything to recompile.

Common mistakes

Common mistakes

1. Forgetting the semicolon after the class

Closing a class with } and no ; makes g++ report "expected ';' after class definition". Some compilers report the problem on the following line instead, which is confusing. Every class ends with };, so check for it whenever you finish one.

2. Forgetting public: in a class

With class Point { int x; int y; }; the members are private, so p.x = 3; in main() fails with "'int Point::x' is private within this context". If you only need a bundle of data, use struct; with a class, choose the public interface on purpose.

3. Leaving built-in members uninitialized

Reading a member like int lessons; before anything assigns it can print a different random number on every run, and it is undefined behavior. Always give such members a default member initializer such as int lessons = 0;.

4. Leaving const off a read-only function

If showInfo() lacks const, calling c.showInfo() through a const Course& c fails with "passing 'const Course' as 'this' argument discards qualifiers". Mark every member function that leaves the object unchanged as const.

Best practices

Best practices

  • Name classes in PascalCase (Course) and objects in camelCase (cppCourse) so readers can tell types from values at a glance.
  • Give every built-in data member a default member initializer.
  • Mark member functions that do not modify the object as const, and pass objects by const reference.
  • Never put using namespace std; in a header file; write std:: in full there.

Mini challenge

Mini challenge: a reading-progress class

Write a Book class that remembers a book's title, total pages and pages read so far, then try it with two objects.

  • Data members title, pages and pagesRead, with pagesRead defaulting to 0
  • read(int n) adds n to pagesRead but never goes past pages
  • percent() const returns the share read as an integer percentage
  • print() const prints "Title: read/pages pages (N%)", and two objects are read independently
book.cpp
#include <iostream>
#include <string>

class Book {
public:
    // TODO: title, pages, and pagesRead (starting at 0)

    void read(int n) {
        // TODO: add n, but cap the result at pages
    }

    int percent() const {
        // TODO: pagesRead as a whole-number percentage of pages
    }

    void print() const {
        // TODO: print "Title: read/pages pages (N%)"
    }
};

int main() {
    // TODO: create two books, read 100 then 50 pages of a 400-page book,
    //       read 500 pages of a 320-page book, and print both
}

Expected: Dune: 150/400 pages (37%) Clean Code: 320/320 pages (100%)

Show hint

To cap, use if (pagesRead > pages) pagesRead = pages; or std::min from <algorithm>. For an integer percentage multiply first, pagesRead * 100 / pages; dividing first gives 0 because of integer division.

Show solution
book.cpp
#include <algorithm>
#include <iostream>
#include <string>

class Book {
public:
    std::string title = "Untitled";
    int pages = 0;
    int pagesRead = 0;

    void read(int n) {
        pagesRead = std::min(pagesRead + n, pages);
    }

    int percent() const {
        return pages == 0 ? 0 : pagesRead * 100 / pages;
    }

    void print() const {
        std::cout << title << ": " << pagesRead << "/" << pages
                  << " pages (" << percent() << "%)\n";
    }
};

int main() {
    Book dune;
    dune.title = "Dune";
    dune.pages = 400;

    Book cleanCode;
    cleanCode.title = "Clean Code";
    cleanCode.pages = 320;

    dune.read(100);
    dune.read(50);
    cleanCode.read(500);

    dune.print();
    cleanCode.print();
}

Quick quiz 1 / 3

Given class Point { int x; int y; };, what happens when main() runs Point p; p.x = 3;?

Quick quiz 2 / 3

What does Course a; a.lessons = 5; Course b = a; b.lessons = 9; std::cout << a.lessons; print?

Quick quiz 3 / 3

What is the actual language difference between class and struct in C++?

What to remember

  • A class is a new type; an object is a value of that type with its own data in memory.
  • obj.member reaches members, and names inside a member function refer to the calling object through this.
  • class defaults to private and struct to public; otherwise they are the same.
  • Give built-in members default values, mark read-only member functions const, and close every class with };.

The Current ISO C++ Standard (C++23) — Standard C++ Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Classes & Objects | Thuta Learning