Lesson 46 of 60 – Classes and Objects in C++
77%

Classes and Objects in C++

A class in C++ is a user-defined data type that combines data members and functions into a single unit. An object is an instance of a class. Classes are one of the most important features of Object-Oriented Programming (OOP).

Note: A class defines the structure and behavior of an object, while an object is an actual instance created from that class.

1. What is a Class?

A class is a blueprint or template for creating objects.

For example, a Student class can describe information such as:

  • Name
  • Age
  • Marks
  • Functions to display student information
class Student {

};

2. What is an Object?

An object is an instance of a class.

class Student {

};

int main() {

    Student student1;

    return 0;
}

Here, Student is the class and student1 is an object of that class.

3. Basic Class Syntax

class ClassName {

    // data members
    // member functions

};

A class definition ends with a semicolon.

4. Creating a Simple Class

class Student {

public:

    std::string name;
    int age;
    float marks;

};

The public keyword makes these members accessible from outside the class.

5. Creating an Object

Student student1;

This statement creates an object named student1 from the Student class.

Multiple objects can also be created:

Student student1;
Student student2;
Student student3;

6. Data Members

Variables declared inside a class are called data members or member variables.

class Student {

public:

    std::string name;
    int age;
    float marks;

};

Here, name, age, and marks are data members.

7. Accessing Data Members

The dot operator . is used to access public members through an object.

Student student1;

student1.name = "Amit";
student1.age = 20;
student1.marks = 85.5;

Values can then be displayed using the same dot operator.

std::cout << student1.name;

8. Member Functions

A function declared inside a class is called a member function.

class Student {

public:

    std::string name;

    void display() {

        std::cout << name;
    }

};

Member functions can work with the data members of the same object.

9. Calling a Member Function

Student student1;

student1.name = "Rahul";

student1.display();

The dot operator is also used to call a member function.

10. Complete Class and Object Example

#include <iostream>
#include <string>

class Student {

public:

    std::string name;
    int age;

    void display() {

        std::cout << "Name: "
                  << name
                  << std::endl;

        std::cout << "Age: "
                  << age;
    }
};

int main() {

    Student student1;

    student1.name = "Amit";
    student1.age = 20;

    student1.display();

    return 0;
}

11. public Access Specifier

Members declared after public: can be accessed from outside the class.

class Student {

public:

    int age;

};

int main() {

    Student student;

    student.age = 20;

    std::cout << student.age;

    return 0;
}

12. private Access Specifier

Members declared after private: cannot be accessed directly from outside the class.

class Student {

private:

    int age;

public:

    void setAge(int a) {

        age = a;
    }

};

A public member function can be used to work with private data.

13. protected Access Specifier

The protected access specifier allows members to be accessed inside the class and by derived classes.

class Parent {

protected:

    int value;

};

Protected members are commonly discussed when learning inheritance.

14. Class Access Specifiers

Specifier Access
public Accessible from outside the class.
private Accessible within the class and related permitted contexts.
protected Accessible within the class and derived classes.

15. Default Access in a Class

Members of a C++ class are private by default.

class Student {

    int age;

};

Here, age is private because no access specifier was provided.

To make it public, write:

class Student {

public:

    int age;

};

16. Encapsulation with a Class

Encapsulation means keeping data and the functions that operate on that data together and controlling access to the data.

class BankAccount {

private:

    double balance;

public:

    void deposit(double amount) {

        balance += amount;
    }

    double getBalance() {

        return balance;
    }
};

17. Setter Function

A setter function is commonly used to assign a value to a private data member.

class Student {

private:

    int age;

public:

    void setAge(int a) {

        age = a;
    }
};

The setter provides controlled access to the private member.

18. Getter Function

A getter function is commonly used to read a private data member.

class Student {

private:

    int age;

public:

    void setAge(int a) {

        age = a;
    }

    int getAge() {

        return age;
    }
};

19. Multiple Objects

Each object created from a class has its own object state.

class Student {

public:

    std::string name;
    int age;

};

int main() {

    Student student1;
    Student student2;

    student1.name = "Amit";
    student1.age = 20;

    student2.name = "Neha";
    student2.age = 19;

    return 0;
}

Changing student1 does not automatically change student2.

20. Constructor Introduction

A constructor is a special member function that is automatically called when an object is created.

class Student {

public:

    Student() {

        std::cout << "Object created";
    }
};

int main() {

    Student student;

    return 0;
}

The constructor is called when student is created.

21. Class with Constructor and Data

class Student {

private:

    std::string name;
    int age;

public:

    Student(
        std::string n,
        int a
    ) {

        name = n;
        age = a;
    }

    void display() {

        std::cout << name
                  << " "
                  << age;
    }
};

int main() {

    Student student("Amit", 20);

    student.display();

    return 0;
}

22. const Member Function

A member function can be declared const when it should not modify the object's non-mutable data members.

class Student {

private:

    int age;

public:

    Student(int a) {

        age = a;
    }

    int getAge() const {

        return age;
    }
};

The const after the function parameter list is part of the member function declaration.

23. Object as a Function Parameter

An object can be passed to a function just like other values.

class Student {

public:

    std::string name;

};

void display(
    const Student& student
) {

    std::cout << student.name;
}

A const reference avoids an unnecessary copy when the function only needs to read the object.

24. Object Pointer

A pointer can store the address of an object.

class Student {

public:

    std::string name;
};

int main() {

    Student student;

    student.name = "Rahul";

    Student* ptr = &student;

    std::cout << ptr->name;

    return 0;
}

The arrow operator -> is used to access members through an object pointer.

25. Class and Object Practical Example

#include <iostream>
#include <string>

class Employee {

private:

    int id;
    std::string name;
    double salary;

public:

    void setData(
        int employeeId,
        std::string employeeName,
        double employeeSalary
    ) {

        id = employeeId;
        name = employeeName;
        salary = employeeSalary;
    }

    void display() {

        std::cout << "ID: "
                  << id
                  << std::endl;

        std::cout << "Name: "
                  << name
                  << std::endl;

        std::cout << "Salary: "
                  << salary;
    }
};

int main() {

    Employee employee;

    employee.setData(
        101,
        "Rahul",
        35000
    );

    employee.display();

    return 0;
}

26. Common Class and Object Mistakes

  • Forgetting the semicolon after a class definition.
  • Trying to access private members directly from outside the class.
  • Forgetting to create an object before calling non-static member functions.
  • Using the wrong object when accessing data.
  • Confusing a class definition with an object.
  • Using . with a pointer instead of ->.
  • Forgetting to specify public: when members need external access.

27. Class vs Object

Class Object
A blueprint or template. An instance of a class.
Defines data and behavior. Contains actual object state.
Used to create objects. Used to work with the class functionality.
Example: Student Example: student1

28. Best Practices for Classes and Objects

  • Use meaningful class names such as Student or Employee.
  • Keep related data and behavior together.
  • Use private data members when direct external access is not required.
  • Provide public functions for controlled access to private data.
  • Use constructors to initialize objects when appropriate.
  • Use const member functions for operations that do not modify the object.
  • Keep classes focused on a clear responsibility.

29. Real-World Uses of Classes

Classes are used to model real-world entities and software concepts.

  • Student: name, age, marks, result functions.
  • Employee: ID, name, salary, employee functions.
  • Bank Account: account number, balance, deposit and withdrawal.
  • Product: name, price, quantity, stock operations.
  • Book: title, author, price, availability.
  • Car: model, speed, start and stop operations.

30. Classes and Objects – Final Summary

Concept Meaning
Class A blueprint or user-defined type containing data and behavior.
Object An instance of a class.
Data Member A variable declared inside a class.
Member Function A function declared inside a class.
public Members accessible from outside the class.
private Members normally accessible only within the class.
protected Members accessible within the class and derived classes.
Constructor A special member function called when an object is created.
Dot Operator Used to access members through an object.
Arrow Operator Used to access members through an object pointer.
class Student {

private:

    std::string name;
    int marks;

public:

    void setData(
        std::string n,
        int m
    ) {

        name = n;
        marks = m;
    }

    void display() {

        std::cout << name
                  << " "
                  << marks;
    }
};

int main() {

    Student student;

    student.setData("Amit", 85);

    student.display();

    return 0;
}

📌 Key Points

  • A class is a blueprint for creating objects.
  • An object is an instance of a class.
  • Classes can contain data members and member functions.
  • The dot operator is used to access members through an object.
  • C++ classes are private by default.
  • public, private, and protected control member access.
  • Encapsulation helps control access to class data.
  • Constructors are automatically called when objects are created.
  • Objects can be passed to functions and accessed through pointers.
  • Classes and objects are fundamental concepts of Object-Oriented Programming.

🧠 Quick Quiz

Question: What is an object in C++?