Classes and objects are the foundation of Object-Oriented Programming in C++. A class is like a blueprint for creating objects. An object is an instance of a class, containing real values instead of placeholders.
A class in C++ is defined using the class
keyword. It can have data members (variables) and member functions (methods).
#include <iostream> using namespace std; // Class definition class Student { public: string name; int age; void introduce() { cout << "Hi, I am " << name << " and I am " << age << " years old." << endl; } }; int main() { Student s1; // Object creation s1.name = "Rahul"; s1.age = 18; s1.introduce(); // Method call return 0; }
Hi, I am Rahul and I am 18 years old.
class Student
defines a template for student data.name
and age
are data members (attributes).introduce()
is a member function (method) of the class.s1
is an object of the class Student
.s1.name = "Rahul"
assigns values to the object’s data members.Access specifiers define who can access the class members:
public
: Accessible from outside the class.private
: Accessible only inside the class (default).protected
: Accessible inside the class and by derived classes.You can create multiple objects from one class:
Student s1, s2; s1.name = "Amit"; s2.name = "Priya";
Classes are user-defined data types, and objects are variables of that type. This structure brings modularity, clarity, and reuse to your code — making C++ powerful for real-world applications.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!