What is object-oriented programming (OOP) and how is it implemented in C++?

  • Object-oriented programming (OOP) is a programming paradigm that is based on the concept of objects. An object is an instance of a class that contains data and behavior. In OOP, programs are designed by creating classes that define the data and behavior of objects, and then creating instances of those classes.

  • C++ is a popular programming language that supports object-oriented programming. In C++, classes are defined using the class keyword, and objects are created using the new keyword. Here’s an example of a simple class definition in C++:
class Person {
  public:
    string name;
    int age;
    void say_hello() {
      cout << "Hello, my name is " << name << " and I'm " << age << " years old." << endl;
    }
};
  • In this example, we have defined a class called Person that has two member variables: a string called name and an integer called age. The class also has a member function called say_hello that prints a message using the name and age member variables. To create an object of the Person class, we would use the following code:
Person person;
person.name = "John";
person.age = 30;
person.say_hello();
  • This code creates an object of the Person class called person, sets its name and age member variables, and then calls the say_hello member function to print a message.
  • In C++, objects can also be created dynamically using the new keyword, like this:
Person* person_ptr = new Person();
person_ptr->name = "Jane";
person_ptr->age = 25;
person_ptr->say_hello();
  • This code creates a new Person object dynamically using the new keyword and assigns it to a pointer called person_ptr. The -> operator is used to access the member variables and member functions of the object through the pointer.

C++ OOP’s supports the four main principles : encapsulation, inheritance, polymorphism, and abstraction.

Encapsulation

  • Encapsulation is one of the fundamental concepts of object-oriented programming (OOP) that refers to the practice of hiding the implementation details of an object from the outside world, and providing a simple and consistent interface for accessing its functionality. This helps to improve the maintainability, flexibility, and security of software systems, and enables developers to build complex programs by dividing them into smaller, more manageable modules.

  • In C++, encapsulation can be achieved through the use of classes and access modifiers, such as public, private, and protected. By default, all members of a class are private, which means they can only be accessed within the same class, and not from outside. However, public members can be accessed from anywhere, while protected members can be accessed only by derived classes.
  • Here is an example of encapsulation in C++:
#include <iostream>
using namespace std;

class BankAccount {
  private:
    double balance;
  public:
    BankAccount(double initial_balance) {
      balance = initial_balance;
    }
    void deposit(double amount) {
      balance += amount;
    }
    void withdraw(double amount) {
      if (balance >= amount) {
        balance -= amount;
      } else {
        cout << "Insufficient funds!" << endl;
      }
    }
    double get_balance() const {
      return balance;
    }
};

int main() {
  BankAccount my_account(1000.0);
  cout << "Current balance: $" << my_account.get_balance() << endl;
  my_account.deposit(500.0);
  cout << "New balance: $" << my_account.get_balance() << endl;
  my_account.withdraw(2000.0);
  cout << "Final balance: $" << my_account.get_balance() << endl;
  return 0;
}

In this example, we have defined a class BankAccount that represents a simple bank account. The private member variable balance stores the current balance of the account, while the public member functions deposit, withdraw, and get_balance provide a simple interface for interacting with the account.

Note that the balance variable is declared as private, which means it cannot be accessed from outside the class. Instead, we use the public member functions to interact with it. This ensures that the internal state of the object is protected from unauthorized access or modification, and provides a simple and consistent interface for working with the object.

Inheritance

  • In C++, inheritance is a mechanism that allows a class to inherit properties (data members and member functions) from another class, called the base class or parent class. The class that inherits the properties is called the derived class or child class.
  • Inheritance is used to create a hierarchy of classes, where the derived classes inherit properties from their base class and add new properties specific to themselves.
  • Here is an example:
// Base class
class Shape {
  public:
    void setWidth(int w) {
      width = w;
    }
    void setHeight(int h) {
      height = h;
    }
  protected:
    int width;
    int height;
};

// Derived class
class Rectangle: public Shape {
  public:
    int getArea() {
      return (width * height);
    }
};

int main() {
  Rectangle rect;
  rect.setWidth(5);
  rect.setHeight(7);
  cout << "Area of the rectangle is: " << rect.getArea() << endl;
  return 0;
}

In this example, the Shape class is the base class, and it has two data members (width and height) and two member functions (setWidth() and setHeight()). The Rectangle class is the derived class, and it inherits the width and height data members from the Shape class, and adds a new member function getArea() to calculate the area of the rectangle.

There are several types of inheritance in C++:

  • Single Inheritance: A derived class inherits properties from a single base class.
  • Multiple Inheritance: A derived class inherits properties from multiple base classes.
  • Hierarchical Inheritance: Multiple derived classes inherit properties from a single base class.
  • Multilevel Inheritance: A derived class is used as the base class for another derived class.
  • Hybrid Inheritance: A combination of two or more types of inheritance.

Polymorphism

Polymorphism is the ability of an object to take on different forms or have multiple behaviors. In C++, polymorphism is achieved through two mechanisms: function overloading and virtual functions.

  • Function Overloading: Function overloading allows us to define multiple functions with the same name, but with different parameters or argument types. The compiler selects the appropriate function to call based on the number and types of arguments provided.
  • Example:
#include <iostream>
using namespace std;

class Calculator {
   public:
      int add(int a, int b) {
         return a + b;
      }
      double add(double a, double b) {
         return a + b;
      }
};

int main() {
   Calculator calc;
   cout << calc.add(1, 2) << endl;       // calls int add(int a, int b)
   cout << calc.add(1.5, 2.5) << endl;   // calls double add(double a, double b)
   return 0;
}
  • Virtual Functions: Virtual functions allow a derived class to provide its own implementation of a function that is already defined in its base class. This means that when we call a virtual function on a pointer or reference to a base class object, the correct function implementation in the derived class will be called.
#include <iostream>
using namespace std;

class Shape {
   public:
      virtual void draw() {
         cout << "Drawing a shape." << endl;
      }
};

class Circle : public Shape {
   public:
      void draw() {
         cout << "Drawing a circle." << endl;
      }
};

int main() {
   Shape* shapePtr;
   Circle circleObj;
   shapePtr = &circleObj;

   shapePtr->draw();   // calls draw() function of Circle class
   return 0;
}

In the above example, the Shape class has a virtual function draw() which is overridden by the derived Circle class. When draw() is called on the shapePtr pointer, it calls the draw() function of the Circle class, which outputs “Drawing a circle.” to the console.

Abstraction

  • Abstraction is a fundamental concept in object-oriented programming (OOP) that allows programmers to focus on essential features of an object or a group of objects while ignoring less important details. In C++, abstraction can be achieved through the use of abstract classes and pure virtual functions.
  • An abstract class is a class that cannot be instantiated, but can be used as a base class to derive other classes. A pure virtual function is a function that has no implementation in the base class, but must be implemented in any derived class. The use of abstract classes and pure virtual functions helps to create a hierarchy of related classes that share common characteristics.
  • Here is an example of abstraction in C++:
#include <iostream>

using namespace std;

// Abstract class
class Shape {
   public:
      virtual double getArea() = 0; // Pure virtual function
      void setWidth(double w) {
         width = w;
      }
      void setHeight(double h) {
         height = h;
      }

   protected:
      double width;
      double height;
};

// Derived class
class Rectangle: public Shape {
   public:
      double getArea() {
         return (width * height);
      }
};

// Derived class
class Triangle: public Shape {
   public:
      double getArea() {
         return (width * height / 2);
      }
};

int main() {
   Rectangle rect;
   Triangle  tri;

   rect.setWidth(5);
   rect.setHeight(10);

   // Print the area of the rectangle
   cout << "Rectangle area: " << rect.getArea() << endl;

   tri.setWidth(5);
   tri.setHeight(10);

   // Print the area of the triangle
   cout << "Triangle area: " << tri.getArea() << endl;

   return 0;
}

In this example, the Shape class is an abstract class that has a pure virtual function getArea(). The Rectangle and Triangle classes are derived classes that implement the getArea() function according to their respective shapes. By using abstraction, we can create a hierarchy of shapes with common characteristics, and we can use the same interface (getArea()) to calculate their areas without worrying about their specific implementations.

Leave a Reply

Your email address will not be published. Required fields are marked *