Classes and Objects
C++ Classes and Objects
Definition: In C++, a Class is a user-defined data type that acts as a blueprint or template for creating objects. An Object is a specific instance of that class. If a class is the architectural drawing of a house, the object is the actual house built from those drawings.
Why: Classes and objects are the fundamental building blocks of Object-Oriented Programming. They allow you to group data (attributes) and functions (methods) into a single logical unit, making code more organized, scalable, and easier to manage as projects grow in complexity.
The Blueprint vs. The Instance
A class defines what data an object will hold and what it can do, but it does not occupy memory until an object is created from it.
| Entity | Role |
|---|---|
| Class | The logical definition or template (e.g., Student). |
| Object | The physical reality in memory (e.g., s1). |
Example: Creating a Student Instance
In this example, we define a Student class with two public attributes and then create an object s1 to store specific information:
#include <iostream> #include <string> using namespace std; // Defining the Class (The Blueprint) class Student { public: // Access specifier: members are accessible from outside string name; // Attribute (variable) int age; // Attribute (variable) }; int main() { // Creating an Object of Student (The Instance) Student s1; // Accessing attributes using the dot operator (.) s1.name = "Ravi"; s1.age = 20; cout << "Student Name: " << s1.name << endl; cout << "Student Age: " << s1.age << endl; return 0; }
Key Notes
- The
publicKeyword: In C++, thepublicaccess specifier is mandatory if you want to access class members from outside the class (like inmain()). By default, all members of a class areprivate. - Dot Operator (
.): This is the standard syntax for accessing an object's variables or functions. You useobjectName.memberName. - Multiple Objects: You can create many objects from a single class (e.g.,
Student s1, s2, s3;). Each object has its own unique copy of the attributes; changings1.namedoes not affects2.name. - Class vs. Struct: While they look similar, the technical difference is that
structmembers are public by default, whereasclassmembers are private by default. Classes are preferred when building complex logic with data protection in mind.
🏋️ Test Yourself With Exercises
Take our quiz on Classes and Objects to test your knowledge.
Browse Quizzes »