Introduction to OOP
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of “objects,” which contain data (attributes) and code (methods). C++ is an object-oriented language that allows modular, maintainable, and reusable code. OOP helps manage complexity in large software systems by organizing code around real-world entities. It promotes encapsulation, inheritance, polymorphism, and abstraction. OOP enhances flexibility and scalability. It also provides a foundation for frameworks, GUI-based systems, simulations, and large-scale applications.
Core Principles of OOP
- Encapsulation
Encapsulation is the process of bundling data and functions that operate on that data within a single unit or class. It helps to restrict direct access to certain components using access specifiers, improving data integrity and security.
Syntax:
class ClassName {
private:
int data;
public:
void setData(int d) { data = d; }
int getData() { return data; }
};
Example:
class Student {
private:
int age;
public:
void setAge(int a) { age = a; }
int getAge() { return age; }
};
Use of protected in Encapsulation
The protected specifier allows access within the class and its derived classes. It supports encapsulation with controlled inheritance.
Example:
class Person {
protected:
int age;
};
class Employee : public Person {
public:
void setAge(int a) { age = a; }
};
- Inheritance
Inheritance allows one class (child/derived) to inherit the attributes and methods of another class (parent/base). It promotes code reusability and supports hierarchical classification.
Syntax:
class Base {
public:
int a;
};
class Derived : public Base {
public:
int b;
};
Example:
class Animal {
public:
void eat() { cout << “Eating…” << endl; }
};
class Dog : public Animal {
public:
void bark() { cout << “Barking…” << endl; }
};
- Polymorphism
Polymorphism means “many forms.” In C++, it allows one interface to be used for different data types. It can be compile-time (function overloading) or runtime (virtual functions).
Function Overloading Example:
class Print {
public:
void show(int a) { cout << “Integer: ” << a << endl; }
void show(string b) { cout << “String: ” << b << endl; }
};
Runtime Polymorphism Example:
class Base {
public:
virtual void display() { cout << “Base class” << endl; }
};
class Derived : public Base {
public:
void display() override { cout << “Derived class” << endl; }
};
- Abstraction
Abstraction means hiding the internal implementation and showing only essential features to the user. It helps reduce complexity and increases efficiency by focusing on what an object does rather than how.
Syntax & Example:
class AbstractDevice {
public:
virtual void turnOn() = 0; // Pure virtual function
};
class Fan : public AbstractDevice {
public:
void turnOn() override { cout << “Fan turned on.” << endl; }
};