Skip to main content
C++ Fundamentals for Beginners to Advanced
CHAPTER 15 Beginner

Classes and Objects in C++

Updated: May 17, 2026
5 min read

# CHAPTER 15

Classes and Objects

1. Introduction

In Chapter 13, we learned that a struct groups data together. A Class takes this further by grouping both *data* (attributes) and *functions* (methods) into a single unit, while also hiding data from the outside world for security.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Define a Class and instantiate Objects.
  • Understand and apply Access Modifiers (public, private, protected).
  • Define Member Functions inside and outside a class.
  • Understand static class members.

3. Defining a Class and Object

A class is defined using the class keyword. Just like a struct, it must end with a semicolon.
cpp
1234567891011121314151617181920212223242526272829
#include <iostream>
#include <string>
using namespace std;

// 1. Define the Class (The Blueprint)
class Car {
  public: // Access modifier (explained below)
    string brand;
    int year;
    
    // Member function (Method)
    void honk() {
        cout << "Beep beep!" << endl;
    }
};

int main() {
    // 2. Create an Object (The physical car)
    Car myCar;
    
    // 3. Access attributes and methods using the dot (.) operator
    myCar.brand = "Toyota";
    myCar.year = 2022;
    
    cout << myCar.brand << " (" << myCar.year << ")" << endl;
    myCar.honk();
    
    return 0;
}

4. Access Modifiers

Access modifiers determine *who* can access the data inside a class. This is the foundation of Encapsulation.
  1. 1. public: Members are accessible from *outside* the class (e.g., inside main()).
  1. 2. private: Members are ONLY accessible from *inside* the class itself. (By default, all members in a C++ class are private).
  1. 3. protected: Similar to private, but can also be accessed by inherited classes (Covered in Chapter 17).
cpp
1234567891011121314151617181920212223242526272829
class BankAccount {
  private:
    double balance; // Hidden from the outside!
    
  public:
    string accountHolder;
    
    // Public method to safely interact with private data
    void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }
    
    void checkBalance() {
        cout << "Balance: $" << balance << endl;
    }
};

int main() {
    BankAccount acc;
    acc.accountHolder = "John";
    // acc.balance = 1000000; // ERROR! Cannot access private member
    
    acc.deposit(500); // Safe way to modify data
    acc.checkBalance();
    
    return 0;
}

5. Member Functions: Inside vs. Outside

You can declare a function inside the class, but define it *outside* the class using the Scope Resolution Operator (::). This keeps the class blueprint clean and readable.
cpp
123456789
class Calculator {
  public:
    int add(int a, int b); // Declaration only
};

// Definition outside the class
int Calculator::add(int a, int b) {
    return a + b;
}

6. Static Members

Sometimes, you want an attribute to be shared across *all* objects of a class, rather than each object having its own copy. This is a static member.
cpp
1234567891011121314151617181920
class Employee {
  public:
    static int employeeCount; // Shared by ALL Employee objects
    
    Employee() {
        employeeCount++; // Increment count when a new object is created
    }
};

// Static variables must be initialized outside the class!
int Employee::employeeCount = 0;

int main() {
    Employee e1;
    Employee e2;
    
    // Access static members using the class name, not the object
    cout << "Total Employees: " << Employee::employeeCount << endl; // Prints 2
    return 0;
}

7. Mini Project: Employee Management

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

class Employee {
  private:
    int id;
    double salary;
    
  public:
    string name;
    
    // Method to set private data
    void setDetails(int empId, double empSalary) {
        id = empId;
        salary = empSalary;
    }
    
    // Method to display data
    void display() {
        cout << "ID: " << id << " | Name: " << name << " | Salary: $" << salary << endl;
    }
};

int main() {
    Employee emp1;
    emp1.name = "Alice";
    emp1.setDetails(101, 75000);
    
    Employee emp2;
    emp2.name = "Bob";
    emp2.setDetails(102, 68000);
    
    emp1.display();
    emp2.display();
    
    return 0;
}

8. Memory-Level Explanation

When you instantiate an object on the Stack (Car myCar;), memory is allocated for its *attributes* (like brand and year). However, memory is not duplicated for its *member functions*. Functions reside in the Text Segment of RAM, and all objects of that class share the exact same function code to save memory.

9. Common Mistakes

  • Forgetting public:: Because classes default to private, if you forget the public: label, you won't be able to use your class in main().
  • Calling non-static functions via Class Name: Car::honk() is invalid unless honk() is a static function. You must call it on an object: myCar.honk().

10. Exercises

  1. 1. Create a Book class with private attributes for title, author, and pages. Create public methods to set and get these values.
  1. 2. In the BankAccount example, add a withdraw() method that ensures the balance doesn't go below 0.

11. MCQ Quiz with Answers

Question 1

What is the default access modifier for members of a class in C++?

Question 2

Which operator is used to access public members of an object?

Question 3

Which access modifier allows members to be accessed from main()?

Question 4

What is the Scope Resolution Operator used for defining functions outside a class?

Question 5

A static class variable is:

Question 6

Where must a static class variable be initialized?

Q7. If class Person { string name; };, can main() access name? a) Yes b) No, because it is private by default Answer: b) No, because it is private by default

Q8. Are member functions duplicated in memory for every object created? a) Yes b) No, objects share the same function code in memory Answer: b) No, objects share the same function code in memory

Question 9

What is a method?

Question 10

Why use private access modifiers?

12. Interview Questions

  • Q: What is the exact difference between a struct and a class in C++?
  • Q: Explain how static member variables differ from normal member variables.
  • Q: Why do we define functions outside the class using :: instead of just writing them inside the class?

13. Summary

Classes bundle data and behavior. Using access modifiers (public, private), you can implement Encapsulation, ensuring sensitive data is only modified through safe, controlled public methods. Static members allow data to be shared across all instances of a class.

14. Next Chapter Recommendation

In Chapter 16: Constructors and Destructors, you will learn how to automatically set up an object the exact moment it is created, and clean it up when it is destroyed.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·