Table of Contents
ToggleClass and Objects in C++: Complete Guide with Examples
Classes and objects in C++ are the fundamental concepts of object-oriented programming (OOP). A class is a user-defined data type that groups data members and member functions into a single unit, while an object is an instance of that class. These concepts help programmers organize code, represent real-world entities, and develop reusable software applications.
In this tutorial, you will learn the definition of classes and objects, their syntax, how to create objects, practical C++ programs, the differences between classes and objects, common mistakes, interview questions, and practice exercises.
1. Introduction to Classes and Objects in C++
C++ supports procedural programming as well as object-oriented programming. In procedural programming, a program is commonly organized around functions, whereas object-oriented programming organizes data and related operations into classes and objects.
For example, a school management system may contain students, teachers, subjects, and examinations. A programmer can create a Student class containing information such as name, age, and roll number, along with functions for displaying student details. Each student can then be represented by a separate object.
Classes and objects make programs easier to organize, maintain, and extend. They are widely used in application development, games, banking software, school management systems, and other software projects.
2. What Is a Class in C++?
A class in C++ is a user-defined data type that combines data members and member functions into one unit. Data members store information, while member functions perform operations on that information.
For example, a Student class may contain data members such as name, age, and rollNo. It may also contain a member function named display() to show the student’s information. A class acts as a blueprint for creating objects. Defining a class establishes its structure and behavior, but does not by itself create ordinary instances of that class.
Example of a Class in C++
#include <iostream>
using namespace std;
class Student {
public:
string name;
int age;
void display() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};
int main() {
return 0;
}In this program, Student is a class. It contains two data members, name and age, and one member function, display(). The public keyword allows these members to be accessed from outside the class. The program defines the class but does not create a Student object yet.
3. Syntax of a Class in C++
The general syntax of a class in C++ is:
class ClassName {
private:
// Private data members and functions
public:
// Public data members and functions
protected:
// Protected data members and functions
};The class definition begins with the class keyword, followed by the class name. The opening and closing braces contain the members of the class. A semicolon is required after the closing brace.
Important Components of a Class
- class: A keyword used to declare a class.
- ClassName: The name given to the class.
- Data members: Variables declared inside the class.
- Member functions: Functions declared or defined inside the class.
- Access specifiers: Keywords that control access to class members.
- Semicolon: Required after the class definition.
4. What Is an Object in C++?
An object in C++ is an instance of a class. It provides a way to use the data members and member functions defined by that class.
For example, if Student is a class, then s1 and s2 can be two objects of that class. Each object can store its own student information.Objects represent individual entities in a program. A Car class can have objects such as car1 and car2, while an Employee class can have objects representing different employees.
Example of an Object in C++
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
string name;
int age;
void display() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};
int main() {
Student s1;
s1.name = "Basant";
s1.age = 18;
s1.display();
return 0;
}Output:
Name: Basant
Age: 18In this example, s1 is an object of the Student class. The dot (.) operator is used to access its public data members and member function.
5. How to Create a Class and Object in C++
Creating and using a class generally involves three steps.
Step 1: Define a class. :: Declare the class and specify its data members and member functions.
Step 2: Create an object.::Â Use the class name followed by an object name.Student s1;Here, Student is the class name and s1 is the object name.
Step 3: Access the members.::Use the dot operator to access public members.s1.name = "Basant";
s1.age = 18;
s1.display();
These statements assign values to the object’s data members and call its member function.
6. Seven Practical C++ Programs Using Classes and Objects
The following examples demonstrate how classes and objects are used in different situations.
Example 1: Student Information
This program stores and displays a student’s name, roll number, and marks.
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
string name;
int rollNo;
float marks;
void display() {
cout << "Name: " << name << endl;
cout << "Roll No: " << rollNo << endl;
cout << "Marks: " << marks << endl;
}
};
int main() {
Student s1;
s1.name = "Basant";
s1.rollNo = 101;
s1.marks = 85.5;
s1.display();
return 0;
}Output:
Name: Basant
Roll No: 101
Marks: 85.5Explanation: The Student class defines three data members and a display() function. The object s1 stores the student’s details and displays them.
Example 2: Creating Multiple Objects
A single class can be used to create multiple objects. Each object can store different values.
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
string name;
int age;
void display() {
cout << name << " - " << age << endl;
}
};
int main() {
Student s1, s2;
s1.name = "Ram";
s1.age = 18;
s2.name = "Sita";
s2.age = 19;
s1.display();
s2.display();
return 0;
}Output:
Ram - 18
Sita - 19Explanation: Both objects belong to the same class, but each maintains its own name and age values.
Example 3: Rectangle Area : A class can contain functions that perform calculations using an object’s data.
#include <iostream>
using namespace std;
class Rectangle {
public:
float length;
float breadth;
float area() {
return length * breadth;
}
};
int main() {
Rectangle r1;
r1.length = 10;
r1.breadth = 5;
cout << "Area = " << r1.area();
return 0;
}Output:
Area = 50Explanation: The Rectangle class contains length, breadth, and the area() member function. The function returns the product of the two dimensions.
Example 4: Employee Details :: Classes are useful for representing employees in an organization.
#include <iostream>
#include <string>
using namespace std;
class Employee {
public:
string name;
int id;
double salary;
void display() {
cout << "Name: " << name << endl;
cout << "ID: " << id << endl;
cout << "Salary: " << salary << endl;
}
};
int main() {
Employee e1;
e1.name = "Ram Kumar";
e1.id = 101;
e1.salary = 35000;
e1.display();
return 0;
}Output:
Name: Ram Kumar
ID: 101
Salary: 35000Explanation: The Employee class groups related information into one unit. A larger employee management application could use multiple objects to represent many employees.
Example 5: Bank Account :: A class can combine account information with operations such as depositing and withdrawing money.
#include <iostream>
using namespace std;
class BankAccount {
private:
double balance = 0;
public:
void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
}
}
void displayBalance() {
cout << "Balance: " << balance << endl;
}
};
int main() {
BankAccount account;
account.deposit(5000);
account.withdraw(1000);
account.displayBalance();
return 0;
}Output:
Balance: 4000Explanation: The balance data member is private, so it cannot be accessed directly from main(). The public member functions provide controlled access to the account balance. This demonstrates a basic application of encapsulation.
Note: This is an educational example, not a complete or secure banking system.
Example 6: Car Information:: A class can represent the properties and behavior of a car.
#include <iostream>
#include <string>
using namespace std;
class Car {
public:
string brand;
int year;
void start() {
cout << brand << " is starting." << endl;
}
};
int main() {
Car car1;
car1.brand = "Toyota";
car1.year = 2024;
cout << "Brand: " << car1.brand << endl;
cout << "Year: " << car1.year << endl;
car1.start();
return 0;
}Output:
Brand: Toyota
Year: 2024
Toyota is starting.Explanation: The Car class combines data about a vehicle with a function representing an action. The object car1 stores the specific vehicle information.
Example 7: Product Price Calculation:: Classes can also be used to calculate the total price of products.
#include <iostream>
#include <string>
using namespace std;
class Product {
public:
string name;
double price;
int quantity;
double totalPrice() {
return price * quantity;
}
};
int main() {
Product p1;
p1.name = "Notebook";
p1.price = 100;
p1.quantity = 5;
cout << "Product: " << p1.name << endl;
cout << "Total Price: " << p1.totalPrice();
return 0;
}Output:
Product: Notebook
Total Price: 500Explanation: The Product class stores the product name, price, and quantity. The totalPrice() function calculates the total cost based on the object’s data.
7. Difference Between Class and Object in C++
A class and an object are closely related, but they are not the same.
| Class | Object |
|---|---|
| A class is a user-defined type. | An object is an instance of a class. |
| It defines data members and member functions. | It uses the structure and behavior defined by the class. |
| It acts as a blueprint. | It represents an individual entity. |
| A class definition does not create ordinary object instances. | Creating an object generally allocates storage for its instance data. |
| The class name identifies the type. | An object name identifies a particular object in the program. |
Example: Student | Example: Student s1; |
Real-life example: A house design is similar to a class, while individual houses built from that design are similar to objects. The design specifies the structure, while each house is a separate instance.
8. Access Specifiers in C++
Access specifiers control how class members can be accessed. C++ provides three main access specifiers: public, private, and protected.
Public
Public members can be accessed from outside the class through an object, subject to the usual rules of the language.
class Student {
public:
int age;
};Private
Private members can be accessed directly only by member functions and friends of the class. They are commonly used to protect an object’s internal data.
class Student {
private:
int age;
};Protected
Protected members can be accessed by member functions and friends of the class and by members of derived classes, subject to inheritance access rules.
class Student {
protected:
int age;
};Important: Class members are private by default. Therefore, if no access specifier is written, members declared in a class are private.
9. Memory Allocation for Objects in C++
When an object is created, storage is generally allocated for its non-static data members. Different objects of the same class normally maintain separate copies of their instance data.
Consider this example:
class Student {
public:
int age;
};
int main() {
Student s1;
Student s2;
s1.age = 18;
s2.age = 20;
return 0;
}Here, s1 and s2 are two separate objects. Changing the age value of s1 does not change the value stored in s2.
Member functions are part of the class definition and are not ordinarily duplicated for each object. Static data members, unlike non-static data members, are shared by all objects of the class.
10. Advantages of Classes and Objects in C++
The major advantages of using classes and objects are:
- Code organization: Related data and functions are grouped together.
- Code reusability: A class can be used to create multiple objects.
- Data protection: Access control helps prevent unauthorized direct access to internal data.
- Maintainability: Well-organized classes make programs easier to update and debug.
- Real-world modeling: Classes can represent students, employees, products, vehicles, and other entities.
- Encapsulation: Data and the operations that work on it can be combined into a single unit.
- Support for OOP: Classes provide the foundation for inheritance, polymorphism, and other object-oriented programming techniques.
11. Common Mistakes When Using Classes and Objects
Beginners often make the following mistakes while writing C++ programs.
Mistake 1: Forgetting the Semicolon
Incorrect:
class Student {
public:
int age;
}Correct:
class Student {
public:
int age;
};A class definition must end with a semicolon.
Mistake 2: Accessing a Private Member Directly
Incorrect:
class Student {
private:
int age;
};
int main() {
Student s1;
s1.age = 18;
}This code produces an access error because age is private.
To correct it, use a public member function to set or retrieve the value.
Mistake 3: Using the Wrong Operator
The dot operator (.) is used to access members through an ordinary object.
Student s1;
s1.display();The arrow operator (->) is used to access members through a pointer to an object.
Mistake 4: Using Uninitialized Values
A built-in data member such as an int may contain an indeterminate value if it has not been initialized. Initialize data members before reading them.
Mistake 5: Confusing a Class with an Object
Declaring a class defines a type; it does not automatically create an ordinary object.
class Student {
public:
int age;
};
Student s1;In this example, Student is the class and s1 is an object.
12. Practice Questions on Classes and Objects in C++
Test your understanding with the following questions.
Short-Answer Questions
- What is a class in C++?
- What is an object in C++?
- Write the general syntax of a class.
- What are data members and member functions?
- What is the purpose of the dot operator?
- Name the three access specifiers in C++.
- What is the difference between a class and an object?
- Can multiple objects be created from a single class?
Programming Questions
- Write a C++ program to create a
Studentclass with name, roll number, and marks. - Write a program using a
Rectangleclass to calculate area and perimeter. - Create an
Employeeclass with employee ID, name, and salary, and display its details. - Write a program to create two
Carobjects with different brands and manufacturing years. - Create a
BankAccountclass with deposit, withdrawal, and balance-display functions.
Output-Prediction Question
What will be the output of the following program?
#include <iostream>
using namespace std;
class Number {
public:
int value;
void display() {
cout << value << endl;
}
};
int main() {
Number n1, n2;
n1.value = 10;
n2.value = 20;
n1.display();
n2.display();
return 0;
}Answer:
10
20The two objects maintain separate values for their non-static data members.
13. C++ Classes and Objects Interview Questions and Answers
Q1. What is a class in C++?
A class is a user-defined data type that combines data members and member functions into a single unit.
Q2. What is an object in C++?
An object is an instance of a class that can store its own instance data and use the class’s accessible member functions.
Q3. Can a class have multiple objects?
Yes. A single class can be used to create any number of objects, subject to available resources and language rules.
Q4. What is the default access specifier of a class in C++?
The default access specifier for members of a class is private.
Q5. What is the difference between public and private members?
Public members can be accessed through an object from outside the class, while private members cannot be accessed directly from outside the class.
Q6. What is a member function?
A member function is a function associated with a class that defines behavior for its objects or operates on class data.
Q7. What is encapsulation?
Encapsulation is the bundling of data and related operations into a single unit, with access controls that help protect internal state.
Q8. What is the dot operator in C++?
The dot operator (.) is used to access accessible members through an object.
Q9. Can objects of the same class contain different values?
Yes. Each object normally has its own storage for non-static data members.
Q10. What is the relationship between a class and object?
A class defines the type and structure, while an object is an instance created from that class.
Conclusion
Classes and objects are essential concepts in C++ programming. A class defines the structure and behavior of a type, while an object is an instance of that type that can store its own data and use its member functions.
By practicing examples such as Student, Rectangle, Employee, Car, and BankAccount, beginners can understand how classes and objects are used to solve programming problems. Mastering these concepts provides a strong foundation for learning constructors, destructors, inheritance, encapsulation, and polymorphism.
Continue learning C++ by exploring constructors and destructors, then move on to more advanced object-oriented programming concepts.
Related C++ Tutorials
Author: Er. Basant Kumar Yadav
Website: BasantYadav.com.np
