OOPs (Object Oriented Programming System) | Concepts & Interview Question with Examples

OOPs (Object Oriented Programming System) | Concepts & Interview Question with Examples

10.6K views
Summary
The major purpose of C++ programming is to introduce the concept of object orientation to the C programming language. Object Oriented Programming is a paradigm that provides many concepts such as inheritance, data binding, polymorphism etc.

Object-Oriented Programming in C++: A Deep Dive

Object-Oriented Programming (OOP) is a fundamental paradigm in C++ that allows developers to structure code around objects, which are instances of classes. This approach enhances code reusability, maintainability, and scalability. Let's explore the key concepts of OOP in C++ and how they're applied in real-world scenarios.

Table of Contents

1. Classes and Objects

Classes are the building blocks of OOP in C++. They encapsulate data and behavior into a single unit.

Class Declaration Syntax:

class ClassName {
private:
    // Private members
protected:
    // Protected members
public:
    // Public members
    ClassName(); // Constructor
    ~ClassName(); // Destructor
    // Member functions
};

Objects are instances of classes. They represent real-world entities in your program.

Creating Objects:

ClassName objectName;  // Stack allocation
ClassName* ptrObject = new ClassName();  // Heap allocation

2. Encapsulation

Encapsulation is the bundling of data and the methods that operate on that data within a single unit (class). It restricts direct access to some of an object's components, which is a means of preventing accidental interference and misuse of the methods and data.

Example of Encapsulation:

class BankAccount {
private:
    double balance;
public:
    BankAccount(double initialBalance) : balance(initialBalance) {}
    void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }
    bool withdraw(double amount) {
        if (amount > 0 && balance >= amount) {
            balance -= amount;
            return true;
        }
        return false;
    }
    double getBalance() const {
        return balance;
    }
};

In this example, the balance is private and can only be accessed or modified through public methods, ensuring data integrity.

3. Inheritance

Inheritance allows a class (derived class) to inherit properties and methods from another class (base class). This promotes code reuse and establishes a relationship between classes.

Inheritance Syntax:

class BaseClass {
    // Base class members
};

class DerivedClass : public BaseClass {
    // Derived class members
};

Example of Inheritance:

class Shape {
protected:
    int width;
    int height;
public:
    Shape(int w, int h) : width(w), height(h) {}
    virtual int area() = 0;
};

class Rectangle : public Shape {
public:
    Rectangle(int w, int h) : Shape(w, h) {}
    int area() override {
        return width * height;
    }
};

class Triangle : public Shape {
public:
    Triangle(int w, int h) : Shape(w, h) {}
    int area() override {
        return (width * height) / 2;
    }
};

4. Polymorphism

Polymorphism allows objects of different classes to be treated as objects of a common base class. It enables you to write more flexible and reusable code.

Types of Polymorphism:

  1. Compile-time Polymorphism: Achieved through function overloading and operator overloading.
  2. Runtime Polymorphism: Achieved through virtual functions and inheritance.

Example of Runtime Polymorphism:

class Animal {
public:
    virtual void makeSound() {
        cout << "The animal makes a sound" << endl;
    }
};

class Dog : public Animal {
public:
    void makeSound() override {
        cout << "The dog barks" << endl;
    }
};

class Cat : public Animal {
public:
    void makeSound() override {
        cout << "The cat meows" << endl;
    }
};

int main() {
    Animal* animal1 = new Dog();
    Animal* animal2 = new Cat();

    animal1->makeSound();  // Output: The dog barks
    animal2->makeSound();  // Output: The cat meows

    delete animal1;
    delete animal2;
    return 0;
}

5. Abstraction

Abstraction is the process of hiding complex implementation details and showing only the necessary features of an object. It's achieved through abstract classes and interfaces.

Example of Abstraction:

class AbstractEmployee {
protected:
    string name;
    int id;
public:
    AbstractEmployee(string n, int i) : name(n), id(i) {}
    virtual void calculateSalary() = 0;  // Pure virtual function
    virtual void displayDetails() {
        cout << "Name: " << name << ", ID: " << id << endl;
    }
};

class Manager : public AbstractEmployee {
private:
    double baseSalary;
    double bonus;
public:
    Manager(string n, int i, double bs, double b) : AbstractEmployee(n, i), baseSalary(bs), bonus(b) {}
    void calculateSalary() override {
        cout << "Manager's salary: " << baseSalary + bonus << endl;
    }
};

6. Common Interview Questions

  1. Q: What are the main principles of OOP?
    A: The four main principles of OOP are Encapsulation, Inheritance, Polymorphism, and Abstraction.
  2. Q: Explain the difference between struct and class in C++.
    A: The main difference is the default access specifier. In a struct, members are public by default, while in a class, they are private by default.
  3. Q: What is a virtual function?
    A: A virtual function is a member function that is declared in a base class and can be overridden in derived classes. It's used to achieve runtime polymorphism.
  4. Q: What is the diamond problem in inheritance?
    A: The diamond problem occurs in multiple inheritance when a class inherits from two classes that have a common base class. It can lead to ambiguity in method calls.
  5. Q: Explain the concept of a pure virtual function.
    A: A pure virtual function is a virtual function that has no implementation in the base class and must be implemented by any concrete derived class. It's declared using "= 0" syntax.
  6. Q: What is the difference between overloading and overriding?
    A: Overloading occurs when multiple functions with the same name exist in a class, differing in parameters. Overriding occurs when a derived class provides a specific implementation for a function already defined in its base class.
  7. Q: What is a friend function?
    A: A friend function is a function that is not a member of a class but has access to the private and protected members of the class.
  8. Q: Explain the concept of constructors and destructors.
    A: Constructors are special member functions used to initialize objects of a class. Destructors are used to clean up resources when an object is destroyed.
  9. Q: What is the difference between shallow copy and deep copy?
    A: Shallow copy creates a new object that shares the same memory addresses as the original object for its pointer members. Deep copy creates a new object and recursively copies all pointer objects, creating new memory allocations.
  10. Q: What is an abstract class?
    A: An abstract class is a class that contains at least one pure virtual function. It cannot be instantiated and is used as a base class for other classes.

Understanding these OOP concepts and being able to apply them in C++ is crucial for acing placement interviews. Practice implementing these concepts in code and be prepared to explain them clearly and concisely.

OOPs (Object Oriented Programming System) | Concepts &amp; Interview Question with Examples - Skytup Blog