Object Oriented Programming (OOP) employs objects to represent and manipulate data. C++ supports the features of OOP, such as encapsulation, inheritance, and polymorphism. In this blog post, we’ll discuss the principles of OOP in C++, its advantages, and some examples. If you want to learn about Object Oriented Programming and how it applies to C++ and other languages, this wiki may be useful.
Contents
OOP Example 1 (Encapsulation and Inheritance)
OOP Example 2: Random number generator
OOP Example 3: Fahrenheit to Celsius converter
The Four Pillars of OOP in C++:
The four fundamental pillars of OOP in C++ are encapsulation, inheritance, polymorphism, and abstraction. Let’s take a closer look at each of these pillars:
1. Encapsulation
Encapsulation is the process of enclosing data and behavior within a single unit, such as a class or an object. In C++, access modifiers, including public, private, and protected, are used to restrict access to the members of a class.
Public members can be accessed by any part of the program, while private members can only be accessed by the class itself. Protected members are similar to private members but can be accessed by derived classes.
Encapsulation provides several benefits. It allows the developer to restrict access to sensitive data, making the code more secure. It also helps to prevent unintended changes to the internal state of an object.
2. Inheritance
Inheritance is the process of creating a new class based on an existing class. The new class, called a derived class, inherits the properties and behaviors of the original class, called the base class.
In C++, inheritance is implemented using the “extends” keyword. The derived class can override the properties and behaviors of the base class, or it can add new properties and behaviors.
Inheritance allows developers to reuse code and create complex class hierarchies. For example, a class hierarchy for animals might include a base class for all animals and derived classes for specific types of animals, such as mammals, birds, and fish.
2. Polymorphism
Polymorphism is the process of using a single name or interface to represent multiple types. In C++, polymorphism is achieved through the use of virtual functions.
A virtual function is a function that can be overridden by a derived class, allowing objects of different classes to be treated as if they were the same type. This is called dynamic binding.
Polymorphism allows developers to create generic code that can work with different types of objects. For example, a function that operates on shapes can work with circles, squares, and triangles, as long as they are derived from the same base class.
2. Abstraction
Abstraction is the process of creating a simplified representation of something complex. In C++, abstraction is achieved through the use of abstract classes and interfaces.
An abstract class is a class that cannot be instantiated. It is used to define a common interface for a group of related classes. The abstract class defines a set of methods that must be implemented by any derived class.
An interface is a collection of virtual functions that define a set of behaviors. It is similar to an abstract class, but it does not include any implementation details.
Abstraction allows developers to create modular, reusable code that is easy to maintain and modify.
OOP Example 1: Bank account (using Encapsulation and Inheritance)
#include <iostream>
using namespace std;
class BankAccount {
public:
BankAccount(int account_number, double balance, double interest_rate) {
account_number_ = account_number;
balance_ = balance;
interest_rate_ = interest_rate;
}
virtual double calculateInterest() {
return balance_ * interest_rate_;
}
private:
int account_number_;
double balance_;
double interest_rate_;
};
int main() {
BankAccount account(1234, 5000.0, 0.05);
double interest = account.calculateInterest();
cout << "Interest earned: " << interest << endl;
return 0;
}
Example 1 code output:
Interest earned: 250
This program calculates Simple Interest, which can found through the formula I = P*r*t, where I is the simple interest result, P is the principal, r is the rate, and t is the time over which the interest is applied to the amount of money. This wiki, or a search online for “Simple Interest formula” may be helpful for learning more about Simple Interest.
This program works by defining a class named BankAccount
which encapsulates data and functions related to a bank account (e.g. account_number_
, balance_
, interest_rate_
). Note that for this example, it’s important for the data members to be declared in the private section of the class (at the bottom), which is a way of declaring them for this type of situation, while keeping them inaccessible by code outside the class, which a benefit of encapsulation (like mentioned before).
In the main
function, below the BankAccount
class (which actually runs the code), the account balance is set to 5000, and then the 5 percent interest is applied to it, resulting in $250 of earned interest in the bank account.
Here’s another example program, this one generates 9 random numbers whose values are between 1 and 100:

Example 2: Random number generator
#include <iostream>
#include <random>
class RandomNumberGenerator {
public:
RandomNumberGenerator(int min, int max) {
distribution_ = std::uniform_int_distribution<int>(min, max);
generator_ = std::mt19937(std::random_device()());
}
int getRandomNumber() {
return distribution_(generator_);
}
private:
std::uniform_int_distribution<int> distribution_;
std::mt19937 generator_;
};
int main() {
RandomNumberGenerator rng(1, 100);
for (int i = 0; i < 10; i++) {
std::cout << rng.getRandomNumber() << " ";
}
std::cout << std::endl;
return 0;
}
Example 2 code output:
61 3 77 43 89 63 24 47 52 28
In this program, we define a RandomNumberGenerator
class that encapsulates the functionality of generating random numbers. The constructor of the class takes two arguments: the minimum and maximum values for the range of random numbers to generate. We use the std::uniform_int_distribution
class to create a distribution of integers between the specified minimum and maximum values, and the std::mt19937
class to create a Mersenne Twister random number generator.
The getRandomNumber()
method of the class returns a random number from the distribution by calling the operator()
function of the distribution object with the generator object as an argument.
In the main()
function, we create an instance of the RandomNumberGenerator
class with a range of 1 to 100, and then generate and print 10 random numbers using a for loop.
This program demonstrates how object-oriented programming principles can be used to create modular and reusable code that encapsulates complex functionality.
Here’s another example of a Object Oriented Program, this one is for converting between Fahrenheit and Celsius:
OOP Example 3: Fahrenheit to Celsius converter
#include <iostream>
class TemperatureConverter {
public:
TemperatureConverter(double temperature, char scale) {
if (scale == 'F' || scale == 'f') {
fahrenheit_ = temperature;
celsius_ = (temperature - 32) * 5 / 9;
} else if (scale == 'C' || scale == 'c') {
celsius_ = temperature;
fahrenheit_ = temperature * 9 / 5 + 32;
} else {
std::cout << "Invalid scale." << std::endl;
celsius_ = 0;
fahrenheit_ = 0;
}
}
double getFahrenheit() {
return fahrenheit_;
}
double getCelsius() {
return celsius_;
}
private:
double fahrenheit_;
double celsius_;
};
int main() {
TemperatureConverter tc1(68, 'F');
std::cout << "68 degrees Fahrenheit is " << tc1.getCelsius() << " degrees Celsius." << std::endl;
TemperatureConverter tc2(25, 'C');
std::cout << "25 degrees Celsius is " << tc2.getFahrenheit() << " degrees Fahrenheit." << std::endl;
return 0;
}
68 degrees Fahrenheit is 20 degrees Celsius.
25 degrees Celsius is 77 degrees Fahrenheit.
In this program, we have defined a TemperatureConverter class in this program, which encapsulates the functionality of converting temperatures between Fahrenheit and Celsius. The class constructor takes two arguments: the temperature value and the temperature scale, represented by a character (‘F’ for Fahrenheit, ‘C’ for Celsius).
Inside the constructor, we use a conditional statement to determine the temperature scale and calculate the temperature value in both Fahrenheit and Celsius. The class stores these values in private member variables.
The class includes two methods, getFahrenheit() and getCelsius(), which return the Fahrenheit and Celsius temperature values, respectively.
In the main() function, we create two instances of the TemperatureConverter class: one with a temperature of 68 degrees Fahrenheit and one with a temperature of 25 degrees Celsius. We then call the getCelsius() and getFahrenheit() methods of each object and print the results to the console.
This program demonstrates how to use object-oriented programming principles to create reusable and modular code that encapsulates complex functionality, such as temperature conversion.
Here’s another C++ Object Oriented Program, this one counts the number of words that are entered into the console
OOP Example 4: Word counter
#include <iostream>
#include <string>
using namespace std;
class WordCounter {
public:
WordCounter(string str) : input(str) {}
int countWords() {
int count = 0;
for (int i = 0; i < input.length(); i++) {
if (input[i] == ' ') {
count++;
}
}
return count + 1;
}
private:
string input;
};
int main() {
string inputStr;
cout << "Enter a sentence: ";
getline(cin, inputStr);
WordCounter wc(inputStr);
int wordCount = wc.countWords();
cout << "Number of words: " << wordCount << endl;
return 0;
}
Example 4 code output:
Enter a sentence: Headphones, earbuds, speakers, ways of listening to music come in many shapes and sizes, some are good, some not so much. I have my favorite types, what about you? Do you listen to music? Do you like Speakers, or headphones, or the mini cousin of headphones that are much more portable, and that are for some, as good as a good set of speakers?
Number of words: 64
In this program, the WordCounter
class takes a string as input and has a countWords()
method that counts the number of words in the input string. The countWords()
method loops through each character in the input string and counts the number of spaces to determine the number of words. Finally, the program uses the getline()
function to get a line of input from the user, creates a WordCounter
object with the input string, and calls the countWords()
method to count the number of words. The program then outputs the number of words to the console.
Summary
Object-Oriented Programming in C++ is based on the principles of encapsulation, inheritance, and polymorphism. Encapsulation hides the internal details of an object, while inheritance allows for code reuse and modularity. Polymorphism enables objects to take on different forms, making it easier to write flexible and extensible code. OOP in C++ provides many advantages, including code reusability, modularity, and data hiding. By using OOP in C++, programmers can create robust and efficient code that is easier to maintain and modify.
Conclusion
Thank you for reading this article on Object Oriented Programing in C++, I hope you enjoyed and learned from it, and if you did, our C++, C, C#, or other archives may interest you. If you have any questions or comments, feel free to post them below, and we’ll do our best to reply.