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

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. C++ Course

Lesson 10 of 45 · C++

Lesson 18: Classes and Objects

Duration: 11 min

Classes and Objects\n\nA 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.\n\n---\n\n## Example: Simple BankAccount class\ncpp\nclass BankAccount {\n std::string owner;\n double balance{};\npublic:\n BankAccount(const std::string& name, double initial) : owner(name), balance(initial) {}\n void deposit(double amount) { balance += amount; }\n bool withdraw(double amount) {\n if (amount > balance) return false;\n balance -= amount;\n return true;\n }\n void print() const { std::cout << owner << \" balance: $\" << balance << '\\n'; }\n};\n\nint main() {\n BankAccount acc(\"Alice\", 1000.0);\n acc.deposit(250);\n acc.withdraw(500);\n acc.print();\n return 0;\n}\n\n\nKey concepts demonstrated:\n- Constructor initialises members.\n- this pointer is implicit inside member functions.\n- Const‑correctness (print marked const).\n\n> Tip: Keep member data private and expose only the operations that maintain class invariants.\n\n---\n\n<Alert type="info">C++20 introduced explicit(bool) constructors for more granular control.

Previous: Lesson 17: Structs and EnumsNext: Lesson 19: Constructors and Destructors