For working professionals
For fresh graduates
More
Explore C++ Tutorials: Explori…
1. The Ultimate C++ Guide: C++ Tutorial for Beginners
2. Application of C++
3. C++ Hello World Program
4. C++ Variable
5. Reference Variable in C++
6. Function Overloading in C++
7. Functions in C++
8. Pointer in C++
9. Data Types in C++
10. C++ for Loop
11. While Loop in C++
12. C++ Lambda
13. Loop in C++
14. Switch Case in C++
15. Array in C++
16. Strings in C++
17. Substring in C++
18. Class and Object in C++
19. Constructor in C++
20. Copy Constructor in C++
21. Destructor in C++
22. Multiple Inheritance in C++
23. Encapsulation in C++
24. Single Inheritance in C++
25. Friend Class in C++
26. Hierarchical Inheritance in C++
27. Virtual Base Class in C++
28. Abstract Class in C++
29. Vector in C++
30. Map in C++
31. Pair in C++
32. Initialize Vector in C++
33. Iterators in C++
34. Queue in C++
35. Priority Queue in C++
36. Stack in C++
37. ifstream in C++
38. Exception Handling in C++
39. Memory Management in C++
40. Templates in C++
41. Type Conversion in C++
42. Enumeration in C++
43. Namespace in C++
44. Set Precision in C++
45. Stringstream in C++
46. Recursion in C++
47. Random Number Generator in C++
48. C++ Shell
49. Setw in C++
50. Multithreading in C++
51. Atoi in C++
52. Call by Value and Call by Reference in C++
53. Difference Between C and C++
54. C# vs C++
55. C++ GUI
56. C++ Game Code
57. Class in C++
58. C++ Header Files
59. Power Function in C++
60. Data Hiding in C++
61. Inline Function in C++
62. Getline Function in C++
63. Cin in C++
64. Printf in C++
65. Struct in C++
66. C++ List
67. static_cast in C++
68. C++ Comments
69. Structures in C++
70. C++ Standard Template Library (STL)
71. Virtual Function in C++
72. Sorting in C++
73. Polymorphism in C++
74. Oops Concepts in C++
Now Reading
75. Converting Integers to Strings in C++
76. Differences Between Break and Continue
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.
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.
Here's why I believe OOP is an essential tool for modern software development:
Let us learn about the basic concepts of OOPs in C++.
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().
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.
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.
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.
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.
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.
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.
Objects interact by sending messages (function calls) to each other. This facilitates communication between objects, triggering actions and exchanging information.
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.
Now that we have covered the key concepts of OOPs in C++, let us explore these OOPs concepts in C++ with examples.
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.
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.
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.
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.
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.
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.
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++.
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.
Author
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
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.