C++ Classes / Objects


In C++, everything in Object-Oriented Programming revolves around classes and objects.
If you think of OOP as a way to model real-world systems, then classes are the blueprints, and objects are the actual items created from those blueprints.

Understanding how to create and use classes and objects is the foundation of writing any C++ program that follows OOP principles.

What is a Class?

A class in C++ is a user-defined data type that groups data members (variables) and member functions (methods) together.
It acts as a template or structure from which multiple objects can be created.

Think of a class as a design or blueprint.
For example, the concept of a “Car” is a class — it defines what a car is and what it can do.
A real car like a Honda or BMW is an object created from that class.

Example of a Simple Class

#include <iostream>
using namespace std;

class Car {
public:
    string brand;
    string color;

    void start() {
        cout << "The car has started." << endl;
    }
};

In this example:

  • Car is the class name.

  • brand and color are data members.

  • start() is a member function that performs an action.

What is an Object?

An object is an instance of a class.
Once a class is defined, we can create one or more objects from it to use its properties and methods.

Example of Creating an Object

int main() {
    Car c1;   // object of class Car
    c1.brand = "Toyota";
    c1.color = "Red";
    c1.start();
    cout << "Brand: " << c1.brand << ", Color: " << c1.color << endl;
    return 0;
}

Here, c1 is an object of the class Car.
It has its own values for brand and color, and it can call the start() function.

You can create multiple objects from the same class, each with its own data.

Defining a Class in C++

The general syntax for defining a class is:

class ClassName {
    access_specifier:
        // data members
        // member functions
};

Example

class Student {
public:
    string name;
    int age;
    void introduce() {
        cout << "My name is " << name << " and I am " << age << " years old." << endl;
    }
};

Here:

  • The keyword class defines the class.

  • public: is an access specifier that controls visibility (you’ll learn more about this in the Access Specifiers chapter).

  • Variables name and age store data, while the introduce() function performs an action.

Creating and Using Objects

After defining a class, you can create objects in different ways.

Example 1 – Basic Object

Student s1;   // object declaration
s1.name = "Ananya";
s1.age = 20;
s1.introduce();

Example 2 – Multiple Objects

Student s2, s3;
s2.name = "Kavya";
s2.age = 22;

s3.name = "Priya";
s3.age = 19;

s2.introduce();
s3.introduce();

Each object holds its own copy of the data.

Accessing Class Members

You can access class members using the dot operator (.).

Example:

objectName.memberName;
objectName.memberFunction();

For example:

c1.brand = "Hyundai";
c1.start();

This is how you access variables and functions inside a class using an object.

Member Functions Inside and Outside the Class

In C++, member functions can be defined in two ways:

1. Inside the Class

When defined inside the class, the function is automatically considered inline.

class Student {
public:
    string name;
    void greet() {
        cout << "Hello, my name is " << name << endl;
    }
};

2. Outside the Class

You can define a member function outside the class using the scope resolution operator (::).

class Student {
public:
    string name;
    void greet();   // function declaration
};

// function definition outside class
void Student::greet() {
    cout << "Hello, my name is " << name << endl;
}

This approach keeps the class definition clean, especially when functions are long.

Memory Allocation of Objects

Each object has its own copy of data members, but all objects share the same member functions.

For example:

Student s1, s2;
s1.name = "Nisha";
s2.name = "Ritu";

s1.greet(); // uses Nisha
s2.greet(); // uses Ritu

Both objects use the same greet() function, but operate on different data.

Private and Public Members

C++ allows you to control which class members are accessible from outside using access specifiers.

  • public → members are accessible from outside.

  • private → members are hidden from outside the class.

Example:

class BankAccount {
private:
    int balance;
public:
    void setBalance(int b) {
        balance = b;
    }
    void showBalance() {
        cout << "Balance: " << balance << endl;
    }
};

Here, the balance variable is private, so it can’t be accessed directly.
Instead, we use setBalance() and showBalance()—this is an example of encapsulation.

Objects as Function Arguments

Objects can be passed as parameters to functions, just like variables.

Example

class Box {
public:
    int length;
    int breadth;

    int area() {
        return length * breadth;
    }
};

void display(Box b) {
    cout << "Area: " << b.area() << endl;
}

int main() {
    Box b1;
    b1.length = 10;
    b1.breadth = 5;
    display(b1);
    return 0;
}

Here, the object b1 is passed to the display() function.

Array of Objects

You can also create an array of objects when you need to store multiple similar entities.

Example:

class Student {
public:
    string name;
    int age;
    void display() {
        cout << name << " - " << age << endl;
    }
};

int main() {
    Student s[3];
    s[0].name = "Riya"; s[0].age = 20;
    s[1].name = "Tina"; s[1].age = 21;
    s[2].name = "Nina"; s[2].age = 19;

    for(int i=0; i<3; i++) {
        s[i].display();
    }
    return 0;
}

This approach is useful when managing multiple records like students, employees, or products.

Real-Life Example

Let’s take an example of a BankAccount system:

#include <iostream>
using namespace std;

class BankAccount {
public:
    string holderName;
    int accountNumber;
    double balance;

    void deposit(double amount) {
        balance += amount;
        cout << "Deposited: " << amount << endl;
    }

    void withdraw(double amount) {
        if (amount <= balance)
            balance -= amount;
        else
            cout << "Insufficient balance!" << endl;
    }

    void display() {
        cout << "Holder: " << holderName << ", Account: " << accountNumber 
             << ", Balance: " << balance << endl;
    }
};

int main() {
    BankAccount acc1;
    acc1.holderName = "Anika";
    acc1.accountNumber = 1001;
    acc1.balance = 5000;

    acc1.deposit(1000);
    acc1.withdraw(2000);
    acc1.display();
    return 0;
}

This program models a real bank account using a class, showing how classes and objects simplify code organization.

Summary of the Tutorial

In this tutorial, you learned:

  • What classes and objects are in C++

  • How to define and use them

  • How to access class members

  • The role of public and private members

  • How to define member functions inside or outside a class

  • How to pass objects to functions and create arrays of objects

Classes and objects are the heart of C++. Once you master them, you’ll find it much easier to understand other OOP concepts like constructors, inheritance, and polymorphism.


Practice Questions

  1. Write a C++ program to define a class Student with data members for name, roll number, and marks. Add functions to input and display the details of a student.

  2. Create a class Car with data members brand, model, and price. Write functions to set and get these values using an object.

  3. Define a class Rectangle with data members length and width. Add a member function to calculate and display the area of the rectangle.

  4. Write a C++ program to create a class Employee with data members empName, empID, and salary. Include member functions to assign and show employee details.

  5. Create a class Book that stores the title, author, and price of a book. Write a program to input and display details for multiple books using an array of objects.

  6. Define a class BankAccount with data members for account number and balance. Implement member functions for deposit, withdraw, and display balance.

  7. Create a class Box with private data members length, width, and height. Add a function to calculate volume and display it using an object.

  8. Write a program that defines a class Circle with a member variable radius. Include a member function to calculate and return the area of the circle.

  9. Define a class Person with data members for name and age. Create two objects and display their details using member functions.

  10. Write a C++ program that defines a class Movie with title, director, and year as data members. Include a function to display the movie’s information using objects.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top