OOPs Object Oriented Programming Concepts In C++ - C++ Programming Tutorial
C++ Course / Advanced Topics / OOPs Object Oriented Programming Concepts In C++

OOPs Object Oriented Programming Concepts In C++

BLUF: Mastering OOPs Object Oriented Programming Concepts In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: OOPs Object Oriented Programming Concepts In C++

C++ is renowned for its efficiency. Learn how OOPs Object Oriented Programming Concepts In C++ enables low-level control and high-performance computing in the tutorial below.

The primary objective of C++ programming is to incorporate the principles of object-oriented programming into the C programming language. Object-oriented programming is a methodology that encompasses various principles like inheritance, encapsulation, polymorphism, and more.

The coding paradigm that embodies all elements as objects is identified as a genuinely object-oriented programming language. Smalltalk is acknowledged as the initial genuinely object-oriented programming language.

OOPs (Object Oriented Programming System)

An object refers to a tangible entity like a pen, chair, or table. Object-Oriented Programming (OOP) is a technique or model for structuring a software application through the implementation of classes and objects.

It simplifies the software development and maintenance by providing some concepts:

  • Class
  • Object
  • Inheritance
  • Polymorphism
  • Abstraction
  • Encapsulation
  • 1. Class

The group of items is known as a class, serving as an abstract concept. In C++, a class serves as the cornerstone of Object-Oriented programming. To interact with and utilize the attributes and methods of a custom data type, a class instance needs to be instantiated. The class of an object functions as its design template.

Class Example:

In C++, a class is declared using the keyword class as illustrated in the example below.

Example

Example

#include <iostream>

using namespace std;

class Student {

private:

    string name;

    int age;

public:

    Student(string n, int a) : name(n), age(a) {}

    void display() const {

        cout << "Name: " << name << ", Age: " << age << endl;

    }

};

int main() {

    Student studname("John", 24);

    studname.display();

    return 0;

}

Output:

Output

Name: John, Age: 24

Explanation:

In this instance, the class Student contains private attributes such as name and age, which are set during object initialization through a constructor. The display method is responsible for outputting the student's information and is designated as const to prevent any alteration of the class attributes.

Benefits of Classes:

  • Better Code Organization: Classes structure code logically.
  • Encapsulation and Data Hiding: The combination of Encapsulation and Data Hiding helps administrators regulate data access.
  • Code Reusability: The same class enables developers to create several distinct object instances from it.
  • 2. Object:

Any object that exhibits both state and behavior is classified as an entity, like a chair, pen, table, keyboard, bicycle, and more. These entities can exist in both physical and conceptual forms.

Each occurrence of a class embodies itself as an object. An object is a manifestation of the class it belongs to, symbolizing a tangible entity with data properties and related operations.

Syntax:

It has the following syntax:

Example

class ClassName {

    // Class members

};

int main() {

    ClassName obj;  // Creating an object

    return 0;

}

Object Example:

Let's consider an example to demonstrate the concept of objects in C++.

Example

Example

#include <iostream>

using namespace std;

class Car {

public:

    string brand;

    int speed;

        void showDetails() {

        cout << "Brand: " << brand << ", Speed: " << speed << " km/h" << endl;

    }

};

int main() {

    Car car1;

    car1.brand = "Tesla";

    car1.speed = 150;

    car1.showDetails();

    return 0;

}

Output:

Output

Brand: Tesla, Speed: 150 km/h

Explanation:

In this C++ code snippet, a Car class is outlined featuring a publicly accessible integer speed property along with a function named showDetails. However, a crucial element, the brand member, is missing a declaration within the class. To resolve this issue and prevent a compilation error, it is imperative to include brand as a member variable within the class definition.

Benefits of Objects:

  • Encapsulation of Data: In a C++ object, both storage and data management occur securely through encapsulation.
  • Code Reusability: Objects provide the capability for developers to create modular code that can be used multiple times.
  • Real-World Mapping: Interactive design becomes easier through objects that directly represent real-world elements.
  • 3. Inheritance:

When one object acquires all the properties and behaviours of the parent object, i.e. known as inheritance , it provides code reusability. It is used to achieve runtime polymorphism.

  • Sub Class: Subclass or Derived Class refers to a class that receives properties from another class.
  • Super Class: The term "Base Class" or "Super Class" refers to the class from which a subclass inherits its properties.
  • Reusability: As a result, when we wish to create a new class but an existing class already contains some of the code we need, we can generate our new class from the old class due to inheritance. It allows us to utilize the fields and methods of the pre-existing class.

Syntax:

It has the following syntax:

Example

class BaseClass {

    // Base class members

};

class DerivedClass : public BaseClass {

    // Derived class members

};

Inheritance Example:

Let's consider an example to demonstrate the concept of inheritance in the C++ programming language.

Example

Example

#include <iostream>

using namespace std;

class Vehicle {

protected:

    string brand;

public:

    Vehicle(string b) : brand(b) {}

    void showBrand() const { cout << "Brand: " << brand << endl; }

};

class Car: public Vehicle {

private:

    int speed;

public:

    Car(string b, int s) : Vehicle(b), speed(s) {}

    void showDetails() const {

        showBrand();

        cout << "Speed: " << speed << " km/h" << endl;

    }

};

int main() {

    Car myCar("Hundai", 150);

    myCar.showDetails();

    return 0;

}

Output:

Output

Brand: Hundai

Speed: 150 km/h

Explanation:

This C++ code presents a Vehicle class containing a protected brand property, along with a Car class that extends it by introducing a speed property. The showDetails method within the Car class exhibits both the brand and speed attributes, showcasing the concept of inheritance.

Benefits of Inheritance:

  • Code Reusability: Code Reusability function becomes possible because parent class functionalities can be utilized multiple times.
  • Hierarchical Organization: The hierarchical organization establishes a well-organized system of related classes.
  • Easy Maintenance: The modifications made to base classes automatically benefit derived classes through simple maintenance methods.
  • 4. Polymorphism:

When a single task can be executed in multiple ways, it is referred to as polymorphism. For instance, this can involve persuading customers using various approaches or creating different shapes like rectangles.

Various scenarios can lead to variations in the operation's functionality. The behavior of the operation is influenced by the type of data it operates on.

Syntax:

It has the following syntax:

Example

class Base {

public:

    virtual void functionName() { /* Implementation */ }

};

class Derived : public Base {

public:

    void functionName() override { /* Implementation */ }

};

Polymorphism​​​​​​​ Example:

Let's consider an example to demonstrate polymorphism in C++.

Example

Example

#include <iostream>

using namespace std;

class Animal {

public:

    virtual void makeSound() const { cout << "Animal sound" << endl; }

};

class Dog : public Animal {

public:

    void makeSound() const override { cout << "Bark" << endl; }

};

int main() {

    Animal* animal = new Dog();

    animal->makeSound();

    delete animal;

    return 0;

}

Output:

Explanation:

This code showcases polymorphism by utilizing a pointer to the base class (Animal*) to invoke the overridden makeSound method of the derived Dog class. To maintain correct memory management when deallocating objects dynamically, a virtual destructor is implemented in the Animal class.

Benefits of Polymorphism:

  • Code Flexibility: Due to code flexibility, the system can perform method overriding dynamically.
  • Eliminates Code Duplication: A common interface eliminates duplication because it works for various data types.
  • Improves Extensibility: The technique makes software frameworks expandable when developers need to handle new system needs.
  • 5. Abstraction:

Abstraction involves concealing internal implementation specifics and revealing only the fundamental features to the user. Data abstraction focuses on presenting only essential information to external entities while keeping implementation details hidden. In C++, abstract classes and interfaces are employed to accomplish abstraction.

Syntax:

It has the following syntax:

Example

class AbstractClass {  

public:  

    virtual void functionName() = 0;  // Pure virtual function  

};  

class DerivedClass : public AbstractClass {  

public:  

    void functionName() override {  

        // Implementation  

    }  

}

Abstraction​​​​​​​ Example:

Let's consider an example to demonstrate the concept of abstraction in the C++ programming language.

Example

Example

#include <iostream>

using namespace std;  //using standard namespace

class ATM {  // Abstract base class

public:

    virtual void withdrawMoney(double amount) = 0; // pure virtual function

};

class BankATM : public ATM {  // Derived class

public:

    void withdrawMoney(double amount) override {

        cout << "Processing withdrawal of $" << amount << "" << endl;

    }

};

int main() {  //Main function

    ATM* atm = new BankATM(); // Using abstraction through  base class pointer

    atm->withdrawMoney(80.0);

    return 0;

}

Output:

Output

Processing withdrawal of $80

Explanation:

This C++ code snippet establishes an ATM class containing a withdrawFunds function to exhibit a message for a withdrawal action. Within the main function, an instance of the ATM class is generated and the withdrawFunds method is invoked with a specified amount for demonstration.

Benefits of Abstraction:

  • Simplifies Complex Systems: User interaction with the interface remains simple.
  • Enhances Security: The system protects internal components from user visibility.
  • Improves Maintainability: Changes in implementation do not affect the users of the system.
  • 6. Encapsulation:

In C++, encapsulation is described as the process of binding code and data into a unified entity. Just like how various medicines are enclosed within a capsule for packaging.

Encapsulation is commonly known as the bundling of interconnected data and information into a unified entity. It involves combining data with the corresponding operations that manipulate it within the context of object-oriented programming.

Syntax:

It has the following syntax:

Example

class ClassName 

{ 

private: int data; 

public: void setData(int d) 

{

 data = d; 

} 

int getData() { 

return data; } 

};

Encapsulation Example:

Let's consider an example to demonstrate encapsulation in C++.

Example

Example

#include <iostream>

using namespace std;

class Rectangle {

private:

    int len;   // Data members are private

    int bre;

public:

    // Constructor to initialize data members

    Rectangle(int l, int b) {

        len = l;

        bre = b;

    }

    // Public method

    int getArea() {

        return len * bre;

    }

};

int main() {

    Rectangle rect(12, 8);  // Create object

    cout << "Area of Rectangle = " << rect.getArea();  // Access data through public method

    return 0;

}

Output:

Output

Area of Rectangle = 96

Benefits of Encapsulation:

  • Data Security: It prevents accidental modification of sensitive data.
  • Improved Maintainability: The modified implementation carries no impact on users accessing the class through its interfaces.
  • Modular Code Design: A modular code design structure allows developers to achieve structured code that remains easy to manage.
  • Advantage of OOPs over Procedure-oriented programming language

  • OOP makes development and maintenance easier, whereas in a procedure-oriented programming language, managing code becomes difficult as the project size grows.
  • OOP provides data hiding, whereas in a procedure-oriented programming language, global data can be accessed from anywhere.
  • OOPs provide the ability to simulate real-world events much more effectively. We can provide the solution of real word problems if we are using the Object-Oriented Programming language.
  • Why do we need oops in C++?

There were multiple limitations associated with the initial programming techniques, along with subpar efficiency. The methodology failed to adequately tackle practical challenges due to the inability to recycle code within the program, encountering challenges with accessing global data, and more.

By leveraging classes and objects, object-oriented programming simplifies code maintenance. Through inheritance, code reuse is facilitated, reducing the need for repetitive coding. Concepts such as encapsulation and abstraction also support data hiding within the program.

Why is C++ a partial oops?

The main driving force behind the development of the C++ language was the incorporation of object-oriented aspects from the C language.

The C++ programming language is classified as a semi object-oriented programming language despite its support for OOP principles such as classes, objects, inheritance, encapsulation, abstraction, and polymorphism.

  • In C++, the main function is always positioned outside the class and is mandatory. This means that it is possible to forego the use of classes and objects and have a single main function within the program. This scenario signifies a departure from Pure OOP principles.
  • Global variables in C++ allow access from any object within the program and are defined externally, thereby violating encapsulation. While C++ promotes encapsulation for classes and objects, it does not adhere to this principle for global variables.
  • Conclusion

In summary, we will have developed comprehension regarding the importance of object-oriented programming, the concepts of C++ OOPs, and the core principles of OOPs like polymorphism, inheritance, encapsulation, and more as we go through this tutorial on OOPS Concepts in C++. In addition to exploring examples of polymorphism and inheritance, you have also been introduced to the advantages of C++ OOPs.

Oops Concepts in C++ MCQs

  1. What is the primary advantage of using encapsulation in OOP?
  • It allows multiple inheritance
  • Encapsulation protects underlying code from being visible to program users.
  • The encapsulation technique enables worldwide access to data.
  • The program size expands because of this approach.
  1. In Object-Oriented Programming, what does a class represent?
  • A specific object with attributes
  • A blueprint serves as the foundation to build new objects.
  • Old systems use functions to transform input data.
  • A variable that stores multiple values
  1. Which of the following statements about polymorphism in C++ is true?
  • The design permits functions to carry several possible methods of execution
  • It prevents data hiding
  • It restricts inheritance
  • This approach stops the requirement for objects.
  1. Which of the following option correctly describes inheritance?
  • A class achieves all properties from another class through inheritance.
  • Using private members of a different class represents an improper method of implementation.
  • A function can activate another nested function.
  • A variable which can hold multiple values
  1. What is an object in C++?
  • Data blueprints and function definitions together create a blueprint in C++.
  • Functions operate as discrete entities to carry out distinct tasks.
  • An instance of a class
  • A variable that stores multiple values

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience