Ad Code

Responsive Advertisement

OOPs Concepts | Must Understand Object Oriented Programming topics for Complex Architecture and Scalable Server


C++ is an object-oriented programming language that is widely used in various applications. Object-Oriented Programming (OOP) is a programming paradigm that focuses on objects and classes, rather than procedures and functions. In this article, we will delve deeper into the fundamental concepts of OOP in C++, and explore how they can help to write more organized, efficient, and maintainable code.


Classes and Objects:


A class is a blueprint for creating objects, which are instances of the class. Classes are used to encapsulate data and functionality related to a particular type of object. For example, a class called "Person" could be used to represent information about people, including their name, age, and address. Objects are created from classes by calling their constructors. For instance, you could create a "Person" object called "p1".

Here is a simple example of a class and object in C++:


#include <iostream>
using namespace std;
class Car {
  public:
    string brand;
    string model;
    int year;

    void startEngine() {
      cout << "Engine started." << endl;
    }
};
   
int main() {
  Car myCar;
  myCar.brand = "Toyota";
  myCar.model = "Corolla";
  myCar.year = 2020;

  cout << "Brand: " << myCar.brand << endl;
  cout << "Model: " << myCar.model << endl;
  cout << "Year: " << myCar.year << endl;
  myCar.startEngine();

  return 0;
}


In this example, the Car class is defined with three member variables (brand, model, and year) and one member function (startEngine). A Car object myCar is created and its properties are assigned values. The values of the properties are then displayed and the startEngine function is called, which outputs "Engine started."


Encapsulation:

Encapsulation is a key concept in OOP that helps to keep data and functionality hidden from external code, so that the object can control access to its data. This is achieved through access specifiers, such as "private," "protected," and "public." Data members and member functions declared as private can only be accessed within the class, whereas public members can be accessed from outside the class. The protected access specifier allows access from within the class and its subclasses.
Here's a simple example of encapsulation in action:

#include <iostream>
using namespace std;
class BankAccount {
    private:
        int balance;
        string accountNumber;
    public:
        void setBalance(int amount) {
            balance = amount;
        }

        int getBalance() {
            return balance;
        }

        void setAccountNumber(string number) {
            accountNumber = number;
        }

        string getAccountNumber() {
            return accountNumber;
        }
};

int main() {
    BankAccount myAccount;
    myAccount.setBalance(1000);
    myAccount.setAccountNumber("123456789");
    cout << "My account balance is: $" << myAccount.getBalance() << endl;
    cout << "My account number is: " << myAccount.getAccountNumber() << endl;
    return 0;
}

In this example, we have defined a class BankAccount that has two private data members: balance and accountNumber. These data members cannot be accessed or modified directly from outside the class. Instead, the class provides public member functions setBalance, getBalance, setAccountNumber, and getAccountNumber to interact with these data members.


Inheritance:

Inheritance is a mechanism that allows a new class to inherit the properties and behaviour of an existing class. The existing class is called the base class, and the new class is called the derived class. Inheritance is a useful tool for creating new classes that are similar to existing classes, with some modifications. The derived class can access the members of the base class, and it can also add new members to it. This can help to simplify code and make it easier to maintain. Here's a simple example to illustrate inheritance:

class Animal {
    public:
        void eat() {
            std::cout << "The animal is eating" << std::endl;
        }
};

class Dog : public Animal {
    public:
        void bark() {
            std::cout << "The dog is barking" << std::endl;
        }
};

int main() {
    Dog myDog;
    myDog.eat(); // The animal is eating
    myDog.bark(); // The dog is barking
    return 0;
}


In this example, we have a base class called Animal that has a single member function called eat(). We also have a derived class called Dog that inherits from Animal using the public access specifier. This means that all the public members of Animal are accessible in Dog.

The Dog class adds its own member function called bark(), which is not present in Animal. When we create an object of type Dog, we can call both eat() and bark() on it, even though bark() is not defined in Animal.


Polymorphism:

Polymorphism is another important OOP concept that allows an object to take on multiple forms. This can be achieved through function overloading and operator overloading. Function overloading allows multiple functions with the same name but different parameters. Operator overloading allows operators such as +, -, *, and / to be redefined for custom data types. This makes it possible to write code that is more concise, expressive, and easy to read. here is the example,
class Animal {
    public:
        virtual void makeSound() {
            cout << "The animal makes a sound." << endl;
        }
};

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

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

int main() {
    Animal *animalPtr;
    Cat cat;
    Dog dog;
    animalPtr = &cat;
    animalPtr->makeSound(); // outputs "The cat meows."
    animalPtr = &dog;
    animalPtr->makeSound(); // outputs "The dog barks."
    return 0;
}
In this example, we have a base class Animal with a virtual method makeSound(). We also have two derived classes, Cat and Dog, which both override the makeSound() method. In the main() function, we create objects of the Cat and Dog classes and assign them to a pointer of type Animal. When we call the makeSound() method using the animalPtr pointer, the method that is called depends on the actual object that the pointer is pointing to. This demonstrates polymorphism, as the same method (makeSound()) is being called on objects of different classes (Cat and Dog), but produces different behavior depending on the actual class of the object.

Abstraction:

Abstraction is a process that involves hiding the implementation details of an object and exposing only the necessary information. In C++, abstraction is achieved through abstract classes and interfaces. An abstract class is a class that cannot be instantiated and must be inherited by other classes. Interfaces are similar to abstract classes, but they can only contain pure virtual functions, which are functions without a body. These abstractions allow developers to create complex and flexible software systems, by breaking down complex problems into smaller, simpler parts.
Here is a simple example that demonstrates abstraction:
#include <iostream>
// Abstract class
class Animal {
public:
    virtual void makeSound() = 0;
};
// Concrete class that inherits from Animal
class Dog : public Animal {
public:
    void makeSound() {
        std::cout << "Woof!" << std::endl;
    }
};
// Concrete class that inherits from Animal
class Cat : public Animal {
public:
    void makeSound() {
        std::cout << "Meow!" << std::endl;
    }
};
// Main function
int main() {

    Animal* myDog = new Dog();
    Animal* myCat = new Cat();

    myDog->makeSound();
    myCat->makeSound();

    delete myDog;
    delete myCat;

    return 0;
}

In C++, we use the virtual keyword to define a method as abstract, and the = 0 notation to indicate that the method does not have a default implementation. We also use the public keyword to define the access level of the methods and data members in a class. Additionally, we use pointers to objects and the new and delete keywords to allocate and deallocate memory for objects in dynamic memory.

Code Reusability:

One of the key benefits of OOP in C++ is code reuse. Code reuse is the process of using existing code to implement new functionality, without having to write new code from scratch. This can save time and effort, and make it easier to maintain the code. Code reuse can be achieved in C++ through inheritance and polymorphism, as well as through the use of libraries and frameworks. Function Overloading and Function Overriding are two important concepts in Object-Oriented Programming (OOP) in C++. These concepts are used to achieve code reuse and improve the modularity of code, making it easier to write, maintain, and reuse code. Function Overloading is the process of having multiple functions with the same name but with different parameters. The appropriate function is called based on the number and type of arguments passed to the function. Function overloading is used to provide multiple implementations of a function for different input data types or different numbers of arguments. Here's an example of function overloading in C++:
#include <iostream>
using namespace std;

void print(int x) {
  cout << "Integer: " << x << endl;
}

void print(double x) {
  cout << "Double: " << x << endl;
}

void print(char x[]) {
  cout << "String: " << x << endl;
}

int main() {
  print(10);
  print(10.5);
  print("Hello, World!");
  return 0;
}
In this example, the print function is overloaded three times, each with a different parameter type. When print is called with an integer argument, the first implementation is called. When print is called with a double argument, the second implementation is called. And when print is called with a string argument, the third implementation is called. Function Overriding is the process of having a derived class provide a new implementation of a method that is already defined in the base class. This is done to modify or extend the behaviour of the base class. Function overriding is also known as polymorphism, and it is a powerful feature of OOP in C++. Here's an example of function overriding in C++:
#include <iostream>
using namespace std;

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

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

class Square : public Shape {
  public:
    void draw() {
      cout << "Drawing Square" << endl;
    }
};

int main() {
  Shape* shapes[3];
  shapes[0] = new Shape;
  shapes[1] = new Circle;
  shapes[2] = new Square;
 
  for (int i = 0; i < 3; i++) {
    shapes[i]->draw();
  }

  return 0;
}
In this example, the Shape class has a draw method that is overridden in the Circle and Square classes. The draw method in the Circle class provides a new implementation for drawing a circle, and the draw method in the Square class provides a new implementation for drawing a square. The draw method in each of the classes is called dynamically, based on the actual type of the object, which is determined at runtime. In addition to these core OOP concepts, C++ also supports several advanced features, such as templates, which allow functions and classes to be written in a generic way, so that they can work with any data type. C++ also supports exceptions, which are used to handle errors and exceptions in a structured way. Finally, C++ supports multithreading, which allows multiple threads of execution to run concurrently, which can help to make applications more efficient and responsive. In conclusion, OOP is a powerful programming paradigm that can help to improve the quality, efficiency, and maintainability of code. The concepts of classes and objects, encapsulation, inheritance, polymorphism, abstraction, dynamic binding, memory management, the super keyword, constructors and destructors, code reuse, and advanced features such as templates, exceptions, and multithreading, are all fundamental to OOP in C++, and are essential for developing high-quality software systems.

Post a Comment

0 Comments

Close Menu