×

Principles of Object-Oriented Programming in C++

What is Object-Oriented Programming?

Object-oriented programming is about creating obejcts that represent the real-world entity . In object-oriented programming, objects are created for the class. One of the main objectives of object-oriented programming is to bind together the data and the functions that operate on them up to the point that no other part of the code can access the data except for the function that operates on the data.

Example for object-oriented programming in C++

//This program demonstrates how objects are used in the program 
#include<iostream>
using namespace std;
//Creating a class person with the class keyword.
class person
{
  //This is the private part of the class
    char name[20];
    int id;
    //creating a public part of the code
    //creating a function member
public:
    void getdetails(){}
};
//Creating the main function.
int main()
{
  //creating object for the class person.
   person p1; // p1 is a object
}

Explanation:

The above demonstrates how to use an object in the c++ code. In the above code, we have created a class person; inside the class, we have created a few function members and variables. Then we created the main function and object for the class.

Basic Principles of OOPs

Below are the basic principles of object-oriented programming:

  1. Encapsulation
  2. Data Abstraction
  3. Polymorphism
  4. Inheritance

1. Encapsulation:

The encapsulation of data and its methods or functions is the process by which they are combined. In C++, we can do encapsulation by making the function members in the class private and making the public function access the private functions.

Example:

//This code is written to explain the encapsulation


#include<iostream>
using namespace std;
//creating a class using the class keyword


class Encapsulation
{
	private:
		// data hidden from the outside world
		int x;
		
	public:
		// function to set the value of
		// variable x
		void set(int a)
		{
			x =a;
		}
		
		// function to return the value of
		// variable x
		int get()
		{
			return x;
		}
};


// creating a main function
int main()
{
	Encapsulation obj;
	
	obj.set(5);
	
	cout<<obj.get();
	return 0;
}

Output:

Principles of Object-Oriented Programming In C++

Explanation:

The above code is written to demonstrate how to use encapsulation in c++ code. In the code, we have created a class encapsulation. In the class, we have created a private variable, x then we have created function members get and set public. In the main function, we have created an object for the encapsulation, and then using the function member we have set the values of x and printed the values x. This process of binding together the private and public parts of the code is an example of encapsulation.

2. Abstraction:

A user's attention is diverted from irrelevant information by abstraction. This means that abstraction involves hiding irrelevant information from the user. For example, if we open an app on our phone, the information about how the app opens in the background is hidden from the user. This is known as abstraction. This is very useful as the user will not know the unnecessary information using the abstraction process. We can use private keywords in the code so that other users cannot access the code.

//This code is written to demonstrate how abstraction works in a c++ program
#include <iostream>
using namespace std;
//Creating a class Abstraction using the class keyword.


class Abstraction
{
	private:
		//private only this class can access the private variables
		int a, b;


	public:
//Creating a function member.




		void set(int x, int y)
		{
			a = x;
			b = y;
		}


		void display()
		{
			cout<<"a = " <<a << endl;
			cout<<"b = " << b << endl;
		}
};
//Creating a main function
int main()
{
	//object is created for the Abstraction class
	Abstraction obj;
	obj.set(50, 60);
	obj.display();
	return 0;
}

Output:

Principles of Object-Oriented Programming In C++

Explanation:

This code is written to demonstrate how abstraction works in a c++ program. In the above code, we have created a class in which we have written private parts of the code with some variables. The variables in the private code are only accessible to the code in that class. Inside the main function of the code, we set the value of the variables in the private part of the code using the function members.

3. Inheritance:

Inheritance is the process in which another class inherits one class's properties. When a class "A" has properties of another class "B", then we can access the members in the class "B" in the main function using the class A’s object.

Example:

Here is an inheritance example:

// C++ program to demonstrate inheritance


#include <iostream>
using namespace std;


// base class
class Animal {


   public:
    void eat() {
        cout << "I can eat!" << endl;
    }


    void sleep() {
        cout << "I can sleep!" << endl;
    }
};


// derived class
class Dog : public Animal {
 
   public:
    void bark() {
        cout << "I can bark! Woof woof!!" << endl;
    }
};


int main() {
    // Create an object of the Dog class
    Dog dog1;


    // Calling members of the base class
    dog1.eat();
    dog1.sleep();


    // Calling member of the derived class
    dog1.bark();


    return 0;
}

Output:

Principles of Object-Oriented Programming In C++

Explanation:

The above code is written to demonstrate the inheritance. In the example, we can see that we have created a class, Aminal, with some function members. Again we have created a class with the name Dog and inherited the animal class properties into the Dog class. In the main function, we created an object using the Dog class. Using the Dog class object, we have called function members in the dog class and animal class.

4. Polymorphism:

Polymorphism means having many forms. Polymorphism helps the coder to create an overloading function. Polymorphism means we can create one functions with different definitions.

//This code is written to show how polymorphism works in c++
#include <iostream>


using namespace std;
//Creating a class Animal using the class keyword 
class Animal {
		public:
//Creating a function member of void return type 
void eat(){
cout<<"Eating...";
		}
};
//Creating a class dog and inherting the properties of animal class
class Dog: public Animal
{
 public:
 void eat()
		{           cout<<"Eating bread...";
		}
};
//Creating a main function.
int main(void) {
	 Dog d = Dog();
	 d.eat();
	 return 0;
}    

Output:

Principles of Object-Oriented Programming In C++

Explanation:

In the above code, we have created two classes, Animal and dog, and we have inherited the animal characteristics into the dog class. In the main class, when we created an object for the dog class, we called the function present in the dog class i.e., eat().


Related Topics

Initialize Vector in C++

Initialize Vector in C++  The following comparison operators are defined for vector and those are given below. ==, <, <=, !=, >,>=  This allows you to access the element of a vector using...

3 minutes read.

Accumulate() and partial_sum() in C++ STL Numeric header

The C++ STL's numeric library includes the numeric header. This library provides efficient numeric arrays, support for random number generation, and fundamental mathematical operations and types. Several of the numeric...

3 minutes read.

How to calculate size of string in C++

What is string in C++? In C++, a string is a sequence of characters. The string data type is part of the Standard Template Library (STL) and is defined in the...

4 minutes read.

How to create a button in C++

A button is an option through which a user can control to click a provided input to an application. There are several buttons, each with different styles, to maintain the...

3 minutes read.

Array of Vectors in C++ STL

Prerequisites: C++ STL Arrays and C++ STL Vector. A group of items kept in consecutive memory region is known as an array. It is to group similar objects of the same...

4 minutes read.

Bit Manipulation in C++

The high-level language in which we communicate is not understood by the computer. As a result, there existed a standard mechanism for understanding any instruction sent to the computer. At...

5 minutes read.

OOPs Concepts in C++

C++ Object-Oriented Programming Concepts C++ uses the concept of object-oriented programming. Object Oriented Programming has some prominent features: Object Class Data abstraction Encapsulation Polymorphism Inheritance Message passing Object An object is the basic unit...

2 minutes read.

Armstrong Number Program in C++

Let's first define Armstrong number before writing the C++ program to check whether the number is Armstrong or not. The sum of the cubes of its digits is equal to the...

2 minutes read.

Name Mangling and extern in C++

Name Mangling and Function Overloading: Function overloading is a feature offered by C++. As long as each function accepts various parameters, we can use this to write many functions with the...

4 minutes read.

Approach in C++

Object oriented programming languages like Java or C++ use a bottom-up approach that identifies each object first.  In the bottom-up approach, we create a small problem first, and try to...

6 minutes read.

Top 14 Best Free C++ IDE (Editor & Compiler) for Windows in 2024

Bjarne Stroustrup created the all-purpose object-oriented programming language C++. To develop C++ programs, there are various Integrated Development Environments (IDE) that offer prewritten code templates. These programs automatically modify the...

6 minutes read.

Singleton Design Pattern in C++

Singleton is similar to the global variable. Singleton helps to have only one object of its kind and provides only single access. One of the key features of the singleton...

2 minutes read.

Print Table Using Do while Loop in C++

Multiplication Table In mathematics, a table is created by multiplying a certain number by all of the counting numbers, i.e., 1, 2, 3, 4, 5, 6, and so on. It is...

4 minutes read.

Hybrid Inheritance

C++ Hybrid Inheritance When more than one type of inheritance is combined in single inheritance is called as hybrid inheritance. C++ Hybrid Inheritance Example #include<iostream>   using namespace std;   class Student{       protected:           int rollno;       public:           void getRoll(int a){               rollno=a;           }           void putRoll(void){               cout <<"Roll No: "<< rollno<<endl;           }   };   class Test : public Student{       protected:           float subject1, subject2;       public:           void getMarks(float x, float y){               subject1=x;               subject2=y;           }           void putMarks(void){               cout<< "Marks gain: "<<endl <<"Subject1 =  "<<subject1<<endl<<"Subject2 = "<<subject2 <<endl;           }   };   class Sport{       protected:           float score;       public:           void getScore(float s){               score=s;           }           void putScore(void){               cout<<"Sports score: "<<score<<endl;           }   };   class Result : public Test, public Sport{       float total;       public:           void display(void);   };   void Result:: display(void){       total=subject1+subject2+score;       putRoll();       putMarks();       putScore();       cout<<"Total Score: "<<total<<endl;   }   int main(){       Result stu;       stu.getRoll(10);       stu.getMarks(40,50);       stu.getScore(60);       stu.display();       return 0;   } Output: Roll No: 10 Marks gain: Subject1 = 40 Subject2 = 50 Sports score: 60 Total...

1 minute read.

Implementing the sets without C++ STL containers

Many practical features and tools in C++ support us in programming competitions. One of these parts is a set from the Standard Template Library (STL), which offers an effective way...

6 minutes read.

Multiple Inheritance

C++ Multiple Inheritance Multiple inheritance is such an inheritance in which a derived class inherits properties of more than one base class.     C++ Multiple Inheritance Example In this example, two base classes Square and...

2 minutes read.

Binary Operator Overloading in C++

The Binary Operator Overloading in the C++ programming language will be covered in this part. An operator which comprises two operands to execute a mathematical operation is termed the Binary...

6 minutes read.

C++ References

C++ References An alias is a reference variable that is another name for a variable already in existence. If a relation is initialized with a variable, it is possible to use...

3 minutes read.

Default Constructor

C++ Default Constructor A default constructor is such constructor which does not take any parameter. A constructor initializes the data member when a class object created. If a programmer does not create any...

2 minutes read.

C++ Enumeration

C++ Enumeration In C++, Enum is a special data type that contains some fixed sets of components that have various applications in the programming. Enum works fine with fixed constant sets...

3 minutes read.