OOPs Assisng
OOPs Assisng
Encapsulation :
Encapsulation is the concept of bundling data and methods that operate on that data into a
single unit called a class. It helps to protect data from unauthorized access by using
access specifiers such as private, protected, and public.
#include <iostream>
using namespace std;
class Student {
private:
string name;
int age;
double percentage;
public:
void setName(string n) {
name = n;
}
string getName() {
return name;
}
void setAge(int a) {
if (a > 0)
age = a;
else
cout << "Invalid age!" << endl;
}
int getAge() {
return age;
}
void setPercentage(double p) {
if (p >= 0 && p <= 100)
percentage = p;
else
cout << "Invalid percentage!" << endl;
}
double getPercentage() {
return percentage;
}
};
int main() {
Student s;
return 0;
}
// Base class
class Person {
public:
void displayInfo() {
cout << "I am a person." << endl;
}
};
int main() {
// Creating object of Student
Student s;
return 0;
}
// Base class
class Person {
public:
// Function Overriding Example
virtual void introduce() {
cout << "I am a person." << endl;
}
};
// Derived class
class Student : public Person {
public:
// Overriding the base class method
void introduce() override {
cout << "I am Shobhit Mishra, a student." << endl;
}
int main() {
// Base class pointer pointing to derived class object for overriding
Person* p;
Student s;
p = &s;
p->introduce(); // Calls Student's overridden method
// Abstract class
class Shape {
public:
// Pure virtual function (makes this class abstract)
virtual void area() = 0;
};
// Derived class 1
class Rectangle : public Shape {
public:
void area() override {
cout << "Area of Rectangle: length * breadth" << endl;
}
};
// Derived class 2
class Circle : public Shape {
public:
void area() override {
cout << "Area of Circle: π * radius * radius" << endl;
}
};
int main() {
// Shape s; // ❌ Error: Cannot instantiate abstract class
Rectangle r;
Circle c;
shapePtr = &c;
shapePtr->area();
return 0;
}
// Base class
class Person {
public:
// Virtual function
virtual void show() {
cout << "I am a person." << endl;
}
};
// Derived class
class Student : public Person {
public:
// Overriding the virtual function
void show() override {
cout << "I am Satyam Guptaa, a student." << endl;
}
};
int main() {
// Base class pointer
Person* personPtr;
return 0;
}