Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Lesson 18: Classes and Objects | C++ Course lesson | BraveProgrammer
  1. Courses
  2. /
  3. C++ Course

Lesson 18 of 45

·C++

Lesson 18: Classes and Objects

11 min

Course progress40%

What you'll learn

Keep these ideas in mind as you work through the lesson.

4 points
  • Member variables and functions
  • Access specifiers (public, private, protected)
  • Object instantiation syntax
  • The `this` pointer usage

Classes and Objects

A class defines a type consisting of data members (state) and member functions (behaviour). Objects are instances of classes. Encapsulation hides internal details behind a public interface.


Example: Simple BankAccount class

class BankAccount {
    std::string owner;
    double balance{};
public:
    BankAccount(const std::string& name, double initial) : owner(name), balance(initial) {}
    void deposit(double amount) { balance += amount; }
    bool withdraw(double amount) {
        if (amount > balance) return false;
        balance -= amount;
        return true;
    }
    void print() const { std::cout << owner << \" balance: $\" << balance << '\
'; }
};

int main() {
    BankAccount acc(\"Alice\", 1000.0);
    acc.deposit(250);
    acc.withdraw(500);
    acc.print();
    return 0;
}

Key concepts demonstrated:

  • Constructor initialises members.
  • this pointer is implicit inside member functions.
  • Const‑correctness (print marked const).

Tip: Keep member data private and expose only the operations that maintain class invariants.


<Alert type="info">C++20 introduced explicit(bool) constructors for more granular control.

Make it stickPractice what you've learned1 quiz · 2 practical tests · Optional activities from C++ CourseBrowse activities
Previous lessonLesson 17: Structs and EnumsContinue to lesson 19Lesson 19: Constructors and DestructorsBack to C++ Course curriculum