C++ Classes and Objects
What Are Classes in C++?
A class in C++ acts like a design template that outlines how specific types of data should be grouped and what actions they can perform. It’s similar to a blueprint used to create buildings—once you have the blueprint (class), you can build multiple buildings (objects) from it.
A class holds two types of members:
- Attributes – Variables that hold information
- Functions – Actions or behaviors that operate on that data
What Is an Object?
An object is a practical version of a class. When you declare an object, you are bringing the class to life by giving it space in memory and using its features.
Think of a class as a recipe, and an object as the cake baked from it. One recipe can create multiple cakes, just like one class can create many different objects.
Declaring a Class
class Phone {
public:
string brand;
int price;
void display() {
cout << "Brand: " << brand << ", Price: " << price << endl;
}
}; - class Phone: We're defining a new type called Phone
- string brand and int price: These store the phone's brand name and price
- display(): Function to show the stored data
Using the Class
#includeusing namespace std; class Phone { public: string brand; int price; void display() { cout << "Brand: " << brand << ", Price: " << price << endl; } }; int main() { Phone p1; // Create an object of Phone p1.brand = "Samsung"; p1.price = 15000; p1.display(); // Call the display function return 0; }
Explanation
- Phone p1; creates a phone object named p1
- We assign values directly to p1's attributes
- The display() method prints out the object's current state
- The output will be:
- Brand: Samsung, Price: 15000
Key Concepts
- Instantiation: When an object is made from a class, it’s said to be “instantiated.”
- Accessing Members: We use the dot (.) operator to reach into the object’s data and functions.
- Modularity: Each object maintains its own set of values, keeping things organized and separated.
Multiple Objects Example
Phone p2; p2.brand = "Apple"; p2.price = 70000; P2.display();
You can create as many objects as needed, each with unique values but based on the same class.
Summary
Classes serve as the architectural plan, while objects are the physical form built from those designs. They allow you to group variables and functions into tidy packages, representing real things like products, accounts, or users. Using this method, C++ helps you structure your programs in a clean, organized, and meaningful way—reducing clutter and boosting clarity.
Prefer Learning by Watching?
Watch these YouTube tutorials to understand C++ Tutorial visually:
What You'll Learn:
- 📌 Lec-42: Introduction to Classes & Objects in C++ Programming | OOPS Concept in Easiest Wayd
- 📌 Classes and Objects in C++