3.4 Features of Object-Oriented Programming

Object-Oriented Programming (OOP) provides powerful features to enhance the modularity, reusability, and functionality of code. This section focuses on operator overloading, data conversion, and inheritance (single, multiple, multilevel, hybrid).


1. Operator Overloading

Operator overloading allows the redefinition of operators for user-defined types (e.g., classes). It helps to perform operations on objects intuitively, similar to primitive data types.

Example: Overloading the + operator for a class representing complex numbers.

#include <iostream>
using namespace std;

class Complex {
    int real, imag;
public:
    Complex(int r = 0, int i = 0) : real(r), imag(i) {}

    // Overload the '+' operator
    Complex operator+(const Complex& obj) {
        return Complex(real + obj.real, imag + obj.imag);
    }

    void display() {
        cout << real << " + " << imag << "i" << endl;
    }
};

int main() {
    Complex c1(3, 4), c2(1, 2);
    Complex c3 = c1 + c2; // Using overloaded '+' operator
    c3.display(); // Output: 4 + 6i
    return 0;
}

2. Data Conversion

Data conversion refers to the process of converting one data type to another. This can involve user-defined types and is achieved by overloading type-casting operators.

Example: Converting an object into an integer.


3. Inheritance

Inheritance allows one class to derive properties and methods from another, promoting code reuse and a hierarchical structure. There are several types of inheritance in C++.


a. Single Inheritance One class inherits from another.


b. Multiple Inheritance A class inherits from more than one base class.


c. Multilevel Inheritance A class inherits from another class, which in turn inherits from another class.


d. Hybrid Inheritance A combination of two or more types of inheritance (e.g., single and multiple). This often involves using a virtual base class to resolve ambiguity.


Conclusion

  • Operator Overloading: Allows custom behavior for operators when used with objects.

  • Data Conversion: Enables implicit or explicit conversion between objects and primitive types.

  • Inheritance: Provides different mechanisms (single, multiple, multilevel, hybrid) to reuse and extend functionality.

Last updated