View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
C++ Tutorial

Explore C++ Tutorials: Explori…

  • 76 Lessons
  • 15 Hours

Oops Concepts in C++

Updated on 30/01/2025464 Views

Object oriented programming (OOPs) Concepts in C++ and Java have been an important part of my software development career. Its elegance and power in modeling real-world problems have consistently inspired me. From my early days of experimenting with classes and objects to architecting large-scale systems, OOP has proven to be an invaluable tool in my arsenal.

OOP might feel like a bit of a shift if you're coming from a purely procedural background. But trust me, the benefits in terms of code clarity, maintainability, and scalability are well worth the investment in learning this powerful approach.

In this tutorial, I'll share insights gained from years of hands-on experience with OOPs concepts in C++, delving into the core concepts that make this paradigm so effective. Let us learn all about object-oriented design and the application of these C++ OOPs concepts.

What is OOP?

Object-oriented programming (OOP) has transformed the way I approach software design. It's a paradigm that shifts focus from procedural code to building blocks called "objects." These objects are self-contained entities that encapsulate data (their attributes) and the code that manipulates that data (methods). Think of objects as mini-programs within your larger application.

Let us imagine that I'm designing a simple drawing application. Using OOP, I might have a Shape class as a base, with derived classes like Circle, Rectangle, and Triangle. Each shape would store its own data (color, position, size) and have methods like draw(), move(), and resize(). Suddenly, my code becomes beautifully organized, and I can easily extend the application with new shapes.

C++ is a powerful language expressly designed to support OOP. From my experience, C++ provides the tools you need to define classes, create objects, implement inheritance, utilize polymorphism, and leverage all the core principles of object-oriented design. It offers a seamless way to translate OOP concepts into robust, efficient code.

Importance of Object-Oriented Design

Here's why I believe OOP is an essential tool for modern software development:

  • Modeling the real world: OOP lets me map software objects to real-world entities or concepts. This makes my code more intuitive, easier to reason about, and aligns better with problem domains.
  • Code reusability: Inheritance and polymorphism are lifesavers! I can create reusable components that can be extended and adapted, promoting efficient development and saving me valuable time.
  • Manageability: Encapsulation keeps my code organized and maintainable. By bundling data and its associated behavior within an object, I reduce complexity and can modify parts of my application without breaking other sections.
  • Scalability: OOP's modularity allows me to build large-scale, complex software systems. Objects provide well-defined interfaces for interaction, making it easier to add new features or refactor existing ones.

Essential OOPs Concepts in C++

Let us learn about the basic concepts of OOPs in C++.

1. OOPs concepts in C++: Classes

Think of a class as a blueprint for creating objects. I like to imagine it as a template that defines the characteristics (data members) and behaviors (member functions) common to a group of objects.

Example: A Car class might have data members like brand, model, color, and member functions like startEngine(), accelerate(), and brake().

2. OOPs concepts in C++: Objects

Objects are the stars of OOP. They're concrete instances of a class. When you create an object of the Car class, you're essentially bringing a digital car to life with its own specific attributes and capabilities.

3. OOPs concepts in C++: Encapsulation

Encapsulation safeguards an object's internal state. The principle is simple: data and the functions that operate on that data reside within the object. Access is controlled, enhancing code security and maintainability.

Example: In our Car class, we might make data members private and provide public 'getter' and 'setter' functions to access and modify them safely.

4. OOPs concepts in C++: Abstraction

Abstraction lets me focus on the 'what' rather than the 'how'. It's about presenting a simplified interface to users, hiding complex implementation details behind the scenes.

Example: The startEngine() function hides the intricate steps of fuel injection and ignition, making it easy for anyone to interact with a Car object.

5. OOPs concepts in C++: Inheritance

Inheritance is a powerful mechanism for creating hierarchies of classes. Derived classes inherit properties and behaviors from a base class, enabling me to build specialized types while promoting code reuse.

Example: We could derive classes like SportsCar, SUV, and Truck from the base Car class. They automatically inherit common features and can add their unique characteristics.

6. OOPs concepts in C++: Polymorphism

Polymorphism means "many forms." It allows me to treat objects of different derived classes in a uniform way through their common base class interface. This flexibility is invaluable when designing extensible systems.

Example: I could have a function drive() that takes a Car object as input. I can pass a SportsCar, an SUV, or any other Car-derived object, and the correct drive() behavior is invoked.

7. OOPs concepts in C++: Dynamic Binding

Dynamic binding determines at runtime which overridden version of a function to call. This empowers me to write code that adapts to different object types without prior knowledge.

8. OOPs concepts in C++: Messaging Passing

Objects interact by sending messages (function calls) to each other. This facilitates communication between objects, triggering actions and exchanging information.

Real-world application example of OOPs concepts in C++

Talking about a real-world application will help me explain basic concepts of oops in C++ much more effectively. I once developed a simplified game engine using OOP. Classes like GameObject, Sprite, Collider, and PhysicsBody formed the foundation.

Inheritance allowed for building specific game object types like Player, Enemy, etc. Also, Polymorphism streamlined collision detection and physics simulations. OOP made the engine modular and extensible, a testament to its power in real-world projects.

Examples of OOPs Concepts in C++

Now that we have covered the key concepts of OOPs in C++, let us explore these OOPs concepts in C++ with examples.

Class and Object Example of OOPs Concepts in C++

Code:

#include <iostream>
#include <string>
class Car {
public:
std::string brand;
std::string model;
void startEngine() {
std::cout << "Engine starting..." << std::endl; // More realistic output
}
};
int main() {
Car myCar;
myCar.brand = "Ford";
myCar.model = "Mustang";
myCar.startEngine();
return 0;
}

Explanation:

This code defines a Car class with attributes like brand and model. The main function creates a Car object (myCar) and interacts with its member variables and functions.

Encapsulation Example of OOPs Concepts in C++

Code:

#include <iostream>
class Account {
private:
double balance;
public:
void deposit(double amount) {
balance += amount;
}
double getBalance() const {
return balance;
}
};
int main() {
Account myAccount;
myAccount.deposit(100.0);
std::cout << "Balance: $" << myAccount.getBalance() << std::endl;
return 0;
}

Explanation:

Here, the Account class keeps the balance private, but provides public methods (deposit and getBalance) to control access and modify the balance safely.

Inheritance Example of OOPs Concepts in C++

Code:

#include <iostream>
class Animal {
public:
virtual void makeSound() {
std::cout << "Generic animal sound" << std::endl;
}
};
class Dog : public Animal {
public:
void makeSound() override {
std::cout << "Woof!" << std::endl;
}
};
int main() {
Dog myDog;
myDog.makeSound();
return 0;
}

Explanation:

The Dog class inherits from Animal and overrides the makeSound() function to provide a specific sound for dogs.

Polymorphism Example of OOPs Concepts in C++

Code:

#include <iostream>
class Shape {
public:
virtual void draw() const = 0;
};
class Circle : public Shape {
public:
void draw() const override {
std::cout << "Drawing a circle" << std::endl;
}
};
int main() {
Shape* myShape;
Circle myCircle;
myShape = &myCircle;
myShape->draw();
return 0;
}

Explanation:

The draw() function is declared pure virtual in the Shape class, forcing derived classes (like Circle) to implement their own version. The base class pointer can hold objects of derived classes, allowing for polymorphic behavior based on the actual object type at runtime.

Dynamic Binding Example of OOPs Concepts in C++

Code:

#include <iostream>
#include <memory> // For smart pointers
class Shape {
public:
virtual void draw() const {
std::cout << "Drawing a generic shape" << std::endl;
}
};
class Circle : public Shape {
public:
void draw() const override {
std::cout << "Drawing a circle" << std::endl;
}
};
class Rectangle : public Shape {
public:
void draw() const override {
std::cout << "Drawing a rectangle" << std::endl;
}
};
int main() {
std::unique_ptr<Shape> shape;
// Select a shape at runtime (example with user input)
int choice;
std::cout << "Enter shape type (1 for circle, 2 for rectangle): ";
std::cin >> choice;
if (choice == 1) {
shape = std::make_unique<Circle>();
} else if (choice == 2) {
shape = std::make_unique<Rectangle>();
} else {
std::cout << "Invalid choice!" << std::endl;
return 1; // Exit if invalid choice
}
shape->draw();
return 0;
}

Explanation:

The Shape class acts as the base class with a virtual draw() function. Circle and Rectangle derive from Shape, providing their specific draw() implementations. The draw() function is declared virtual in the base class. This tells the compiler that dynamic binding should be used for calls to this function.

We use a unique_ptr<Shape> pointer to hold the derived class objects. Smart pointers like unique_ptr help with memory management. The decision of whether to create a Circle or Rectangle is made at runtime based on user input. Because of the virtual function and pointer, the correct draw() version is automatically called, demonstrating dynamic binding.

Message Passing Example of OOPs Concepts in C++

Code:

#include <iostream>
class Button {
public:
void onClick() {
std::cout << "Button clicked!" << std::endl;
}
};
class Window {
private:
Button myButton;
public:
void display() {
myButton.onClick();
}
};
int main() {
Window myWindow;
myWindow.display();
return 0;
}

Explanation:

The Button object is a member of the Window class. When the Window calls display(), it sends a message (calls onClick()) to the Button object, simulating communication between objects.

Wrapping Up

OOP in C++ has been instrumental in my ability to create robust and adaptable software solutions. Its principles offer a powerful framework for managing complexity and building systems that elegantly model real-world scenarios. If you're looking to take your C++ skills to the next level, mastering OOP is an essential step in becoming a truly proficient software engineer.

The more you practice, the more natural and intuitive OOP will become. You can enroll in upGrad’s computer science and software engineering programs such as the Master’s in Computer Science to learn object-oriented programming in C++ and other important concepts of C++.

Frequently Asked Questions

1. What are the 4 principles of OOP C++?

The four core principles of OOP in C++ are encapsulation, abstraction, inheritance, and polymorphism. By understanding these 4 principles, we can find out what is OOPs concept in C++.

2. What are the 7 concepts of OOPs?

The traditional OOP concepts include the four pillars (encapsulation, abstraction, inheritance, polymorphism) plus three more: classes, objects, and message passing.

3. What is the concept of OOP?

Object-oriented programming (OOP) is a programming paradigm based on the concept of grouping data and the code that manipulates it into self-contained units called objects. It is easy to explain OOPs concept in C++ once you understand the 4 pillars of object-oriented design.

4. What is the full form of OOPs?

OOPs stands for Object-Oriented Programming System.

5. Why is C++ called OOPs?

C++ is considered an object-oriented programming language because it provides features and mechanisms that support the core principles of OOP.

6. Is C++ 100% object-oriented?

C++ is not purely object-oriented. It's a hybrid language that allows for both object-oriented and procedural programming styles.

7. Which language is used for OOPs?

Many programming languages support OOP concepts, including C++, Java, Python, C#, Ruby, and others.

8. What is C++ also known as?

C++ is sometimes referred to as "C with Classes" due to its origins as an extension of the C programming language.

image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Start Learning For Free

Explore Our Free Software Tutorials and Elevate your Career.

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.