4. C++ OOP: Classes, Objects, Constructors & Destructors
Comprehensive Guide: Access specifiers (public/private), default & parameterized constructors, destructors & dynamic new/delete
Module 1: Classes, Objects & Access Specifiers
Blueprints and object instances bundling data members and member functions.
🇬🇧 English Definition
A Class is a user-defined blueprint that defines data members and member functions, while an Object is a real-world instance of that class.
🇮🇳 Hinglish Definition
Class ek naksha (blueprint) hota hai, aur Object us nakashe se bani asli cheez hoti hai.
Core Concepts & Rules
- private: Accessible ONLY inside the class.
- public: Accessible from anywhere outside the class.
- protected: Accessible inside the class and derived child classes.
🔍 Line-by-Line Code Breakdown
- Line 1-10: Define Student class with private member name and public setter/getter methods.
- Line 13: Instantiate Student object s1 in main().
using namespace std;
class Student {
private:
string name;
public:
void setName(string n) { name = n; }
string getName() { return name; }
};
int main() {
Student s1;
s1.setName("Instructor Student");
cout << "Student Name: " << s1.getName() << endl;
return 0;
}
Module 2: Constructors, Destructors & Dynamic Memory (new/delete)
Automatic object initialization and resource cleanup.
🇬🇧 English Definition
A Constructor is a special member function executed automatically upon object creation, whereas a Destructor (~ClassName) executes automatically when an object goes out of scope.
🇮🇳 Hinglish Definition
Constructor object bante hi automatically call hokar fields initialize karta hai. Destructor (~Class) object destroy hone par RAM clean karta hai.
Core Concepts & Rules
- Constructor has the exact same name as the class and NO return type.
- Destructor name starts with tilde symbol (~ClassName()).
- new operator allocates heap memory; delete releases heap memory.
🔍 Line-by-Line Code Breakdown
- Line 3-5: Parameterized Constructor initializing course name.
- Line 6-8: Destructor ~Course printing cleanup message.
- Line 12: Instantiate Course c1('C++ OOP') triggers constructor automatically.
using namespace std;
class Course {
public:
string title;
Course(string t) {
title = t;
cout << "Constructor Called for: " << title << endl;
}
~Course() {
cout << "Destructor Executed! Memory Cleaned." << endl;
}
};
int main() {
{
Course c1("C++ OOP Masterclass");
} // c1 goes out of scope here -> Destructor runs
return 0;
}