Chapter 9C++ Tutorial~2 min read
OOP — Classes & Inheritance
Object Oriented Programming
C++ मध्ये OOP च्या 4 pillars आहेत: Encapsulation, Inheritance, Polymorphism, Abstraction. Classes मध्ये data (attributes) आणि behavior (methods) एकत्र असतात. Access modifiers: public, private, protected.
Class आणि Object
Class definition आणि object creation
cpp
#include <iostream>
#include <string>
using namespace std;
class Student {
private: // बाहेरून direct access नाही
string name;
int marks;
public: // बाहेरून access होते
// Constructor — object बनवताना call होतो
Student(string n, int m) : name(n), marks(m) {}
// Default constructor
Student() : name("Unknown"), marks(0) {}
// Getter methods
string getName() const { return name; }
int getMarks() const { return marks; }
// Setter
void setMarks(int m) {
if (m >= 0 && m <= 100) marks = m;
}
// Method
string getResult() const {
return marks >= 40 ? "Pass ✅" : "Fail ❌";
}
// Display
void display() const {
cout << name << " — " << marks
<< " (" << getResult() << ")" << endl;
}
};
int main() {
Student s1("Rahul", 85);
Student s2("Priya", 35);
Student s3; // default constructor
s1.display(); // Rahul — 85 (Pass ✅)
s2.display(); // Priya — 35 (Fail ❌)
s1.setMarks(92);
cout << s1.getName() << ": " << s1.getMarks() << endl;
return 0;
}Inheritance
Base class and derived class
cpp
class Animal {
protected:
string name;
public:
Animal(string n) : name(n) {}
void eat() {
cout << name << " खातो." << endl;
}
virtual void speak() { // virtual — runtime polymorphism
cout << name << " आवाज करतो." << endl;
}
};
// Single inheritance
class Dog : public Animal {
public:
Dog(string n) : Animal(n) {} // parent constructor call
void speak() override { // override — parent method replace
cout << name << " भुंकतो: Woof! 🐕" << endl;
}
void fetch() {
cout << name << " ball आणतो!" << endl;
}
};
class Cat : public Animal {
public:
Cat(string n) : Animal(n) {}
void speak() override {
cout << name << " म्हणतो: Meow! 🐱" << endl;
}
};
int main() {
Dog d("Bruno");
Cat c("Whiskers");
d.speak(); // Bruno भुंकतो: Woof! 🐕
d.eat(); // Bruno खातो. — inherited
d.fetch();
c.speak(); // Whiskers म्हणतो: Meow! 🐱
// Polymorphism — base pointer, derived objects
Animal *a1 = new Dog("Rex");
Animal *a2 = new Cat("Luna");
a1->speak(); // Rex भुंकतो (Dog's speak!)
a2->speak(); // Luna म्हणतो (Cat's speak!)
delete a1; delete a2;
return 0;
}Types of Inheritance in C++
- ▸Single: class B : public A — एकाकडून inherit
- ▸Multiple: class C : public A, public B — दोन parents
- ▸Multilevel: A → B → C — chain
- ▸Hierarchical: A ← B, A ← C — एक parent, multiple children
- ▸Hybrid: combination of above
✅ Key Points — लक्षात ठेवा
- ▸class Name { private: ...; public: ...; };
- ▸Constructor — object बनवताना, Destructor — नष्ट होताना
- ▸class Child : public Parent — inheritance
- ▸virtual — runtime polymorphism enable
- ▸override — parent method replace, compile-time safety
0/11 chapters पूर्ण