- C++ Course Basics
- C++ Tutorial
- C++ Basic Syntax
- C++ Identifiers
- C++ Character Set
- C++ Input/Output Operator
- C++ Variables
- C++ Data Types
- C++ Formatting Output
- C++ Operators
- C++ Assignment Operator
- C++ Type Conversion
- C++ Program Control
- C++ if and if-else
- C++ switch
- C++ loops
- C++ break and continue
- C++ Functions
- C++ Functions
- C++ Prototype and Definition
- C++ Function Call
- C++ Function Types
- C++ Friend Function
- C++ Function Overloading
- C++ Arrays and Strings
- C++ Arrays
- C++ One-Dimensional Arrays
- C++ Strings
- C++ String Functions
- C++ Structures
- C++ Structures
- C++ Nested Structure
- C++ Structure Array
- C++ Pass Structure to Function
- C++ Pointers
- C++ Pointers
- C++ Memory Map
- C++ Declare Initialize Pointers
- C++ Pointers and Structures
- C++ Object-Oriented
- C++ Object-Oriented
- C++ Classes and Objects
- C++ Constructors and Destructors
- C++ Objects as Function Arguments
- C++ Pointers and Objects
- C++ Data Structure
- C++ Linked List
- C++ Stack
- C++ Queues
- C++ File Handling
- C++ File Handling
- C++ Opening and Closing Files
- C++ Steps to Process Files
- C++ Sequential I/O Operations
- C++ Detecting EOF
- C++ File Pointers Random Access
- C++ Binary Files Operations
- C++ Error Handling
- C++ Misc
- C++ typedef
- C++ #define
- C++ Date and Time
- C++ Examples
- C++ Examples
Object Oriented Programming in C++ with Examples
C++ supports procedural programming styles, object-based programming styles, and object-oriented programming styles.
Various programming paradigms
A programming paradigm defines the methodology of designing and implementing programs using the key features and other building blocks (such as keywords, function preprocessor directions, etc.) of a programming language. A programming paradigm gives you an idea of how problems are generally analyzed and solved in a particular programming language.
Procedural Programming
Procedural programming lays more emphasis on procedure than data. As C++ is a superset of C, which uses a procedural programming style, C++ can also be used as a procedural programming language, but with some enhanced features such as tighter type checking, reference variables, inline functions, default arguments, etc.
Object Based Programming
Object-based programming is a newer paradigm that implements some features of object-oriented programming but not all. In object-based programming, data and its associated meaningful functions are enclosed in one single entity, a class. Classes enforce information hiding and abstraction, separating the implementation details (how the process actually occurs) and the uses interface (how the user views and uses it).For example, if you consider a calculator, its interface would include a small display screen and a few buttons that are available to the user, while implementation details, i.e., how actual calculations are taking place, are hidden from the user.
Object Oriented Programming
It provides all of the benefits of object-based programming while overcoming its limitations by implementing inheritance, allowing real-world relationships between objects to be represented programmatically.
Basic Concepts of OOP
Object-oriented programming was created to address the shortcomings of traditional programming approaches. The OOP approach is founded on certain ideas that aid in its goal of overcoming the drawbacks or shortcomings of traditional programming approaches. These are the general concepts of OOP:
Let us now briefly describe each of the above OOP concepts in C++, beginning with "Data abstraction." But before you read what comes after this paragraph, you might want to read the "C++ classes and objects" post to learn more about the idea that comes after this paragraph. Except for "classes and objects," this post covers all four remaining topics.
Data abstraction
The process of representing the essential features without including the implementation details is known as data abstraction.
Members defined with the "PRIVATE" label are not accessible to the outside world or the code that uses the class where the PRIVATE members are declared or defined. Consider the following C++ program as an illustration of data abstraction:
#include<iostream>
using namespace std;
class ADD
{
public:
ADD(int i = 0)
{
tot = i;
}
void addnumber(int num)
{
tot = tot + num;
}
int gettotal()
{
return tot;
}
private:
int tot; // hidden from outside the world
};
int main()
{
ADD aob;
int a, b, c;
cout<<"Enter three numbers: ";
cin>>a>>b>>c;
aob.addnumber(a);
aob.addnumber(b);
aob.addnumber(c);
cout<<"\nTotal = "<<aob.gettotal();
cout<<endl;
return 0;
}
The following snapshot shows the initial output produced by the above C++ program.
Now type a number, say 10, and press the ENTER key, then another number, say 20, and press the ENTER key again, and finally a third number, say 30, and press the ENTER key once more to produce the output shown in the screenshot below:
The member "tot" inside the "PRIVATE" label in the class "ADD" in the preceding program is unknown to the outside world.
In the above code, the "ADD()" method is a constructor that will be automatically called and run when an object of the class is created. However, the above program can also be created without the constructor; the basic version of the previous program is shown below.
#include<iostream> using namespace std; class myClass { private: int tot = 0; public: void addnumber(int num) { tot += num; } int gettotal() { return tot; } }; int main() { myClass myObject; int a, b, c; cout<<"Enter three numbers: "; cin>>a>>b>>c; myObject.addnumber(a); myObject.addnumber(b); myObject.addnumber(c); cout<<"\nTotal = "<<myObject.gettotal(); cout<<endl; return 0; }
If you try to access the member "tot" in the above program using the class object, for example:
myObject.tot;
then it is not accessible. However, you can access all the members that are not defined in the "PRIVATE" label.
Data encapsulation
The term "encapsulation" refers to the method by which data and its associated functions are packaged together. The term "data encapsulation" refers to another name for "data hiding."
Data encapsulation protects sensitive information by combining it with the corresponding functions and sealing the whole thing off from prying eyes. Consider the following code fragment as an illustration of data encapsulation:
class myClass { public: double getVolume(void) { return a*b*c; } private: double a, b, c; };
Because the variables "a," "b," and "c" are private, they can only be accessed by members of the "myClass" class and cannot be accessed in any other part of the same program. That is, anything declared and defined in a class with a "private" label will be hidden from the outside world.
The three access levels available in C++ for displaying and hiding data from the outside world are as follows.
- public: All objects are accessible to the public.
- protected: Access is restricted to members of the same class or their descendants only.
- private: Access is restricted to members of the same class only.
Example
#include<iostream> using namespace std; class myClass { public: void addNum(int num) { tot += num; } int getTot() { return tot; }; private: int tot = 0; }; int main() { myClass ob; int x, y, z; cout<<"Enter the three numbers: "; cin>>x>>y>>z; ob.addNum(x); ob.addNum(y); ob.addNum(z); cout<<"\nSum = "<<ob.getTot(); cout<<endl; return 0; }
The following snapshot shows the sample run of the above example with user inputs of "20," "22," and "43" as three number inputs:
Difference between data abstraction and data encapsulation
While designing a project, complexity can be reduced through a process known as abstraction. In order to protect sensitive information and keep track of who has access to what during the implementation phase of a project, encapsulation is a process that takes place at the code level.
Inheritance
The ability of one class to inherit the properties of another class is referred to as inheritance. The most significant advantage of inheritance is code reuse. Once a base class has been written and tested, it can be used in a variety of situations without the need to redefine or rewrite it. You can add new properties to the derived class without redefining the old one, and you can even redefine a member function of an inherited class.
When discussing "inheritance" in C++, two well-known terms are "derived class" and "base class." The class being inherited from is referred to as the base class, whereas the class inheriting from another class is referred to as the derived class. The base class can be thought of as a parent, whereas the derived class can be thought of as a child.
To inherit, use the ":" symbol. Consider the following code fragment as an example.
class students { public: . . . }; class dsaStudents: public students { . . . };
The class "dsaStudents" in the preceding code fragment inherits the attributes and methods of the class "students." Let me now write a full example program demonstrating the use of inheritance in C++.
#include<iostream> using namespace std; class students { public: long int id; string name; }; class dsaStudents: public students { public: string city; }; int main() { dsaStudents ob; cout<<"Enter the ID: "; cin>>ob.id; cout<<"Enter the name: "; cin>>ob.name; cout<<"Enter the city: "; cin>>ob.city; cout<<"\nID = "<<ob.id; cout<<"\nName = "<<ob.name; cout<<"\nCity = "<<ob.city; cout<<endl; return 0; }
The screenshot below shows a sample run of the above program with the user inputs "40502309," "William," and "Houston" as ID, Name, and City.
You can see in the preceding example that I inherited the class "students" from the "dsaStudents." As a result, I simply created an object of the class "dsaStudents" and accessed its member "city," as well as the members "id" and "name" of the "students" class. There are obvious advantages: there is no need to declare the two members "id" and "name," which are already declared in the class "students." I simply inherited it and made use of their members.
However, I used the keyword "public" before the class name "students" in the above program. This keyword is known as "visibility mode." We can use the words "public" and "protected" before the base or inheriting class. There is another mode, "private," but let me tell you that the base class's private members are not directly accessible to the derived class. The table below briefly describes how to use visibility modes.
If the visibility mode is | Then the inheritable public member in the derived class becomes | and the inheritable protected member in the derived class becomes |
---|---|---|
public | public | protected |
protected | protected | protected |
private | private | private |
Let me now give you another example that will help you better understand the topic "inheritance" in C++.
#include<iostream> using namespace std; class BASE { int a; public: int b; protected: int c; private: int d; }; class DERIVED1: public BASE { int x; }; class DERIVED2: protected BASE { int y; }; class DERIVED3: private BASE { int z; }; int main() { cout<<"Size of 'BASE' class = "<<sizeof(BASE)<<endl; cout<<"Size of 'DERIVED1' class = "<<sizeof(DERIVED1)<<endl; cout<<"Size of 'DERIVED2' class = "<<sizeof(DERIVED2)<<endl; cout<<"Size of 'DERIVED3' class = "<<sizeof(DERIVED3)<<endl; return 0; }
The sample output of this example program is shown in the following snapshot:
In the preceding example, I first created a class called "BASE" in which I declared a variable "a" outside of all labels, then another variable "b" in the public label, another variable "c" in the protected label, and finally a variable "d" in the private label. Because the size of "int" in my 64-bit computer architecture system is 4, four "int" variables make a total size of 16, so the output regarding the size of the "BASE" class is 16.
And, because I declared one variable, "x," "y," and "z," in each derived class, "DERIVED1," "DERIVED2," and "DERIVED3," As a result, the size of these classes is 20, because there are five "integer" variables total, including the variables defined in these classes and the variables available in the BASE class.
Polymorphism
Polymorphism in C++ refers to the ability to take on multiple shapes and behaviors. Inheritance and class hierarchy are necessary conditions for polymorphism to take place. As an example of polymorphism in C++, consider the following program:
#include <iostream> using namespace std; class base { public: void myFunction() { cout<<"I'm inside fresherearth's myFunction()\n"; } }; class derivedOne : public base { public: void myFunction() { cout<<"I'm inside derivedOne's myFunction()\n"; } }; class derivedTwo : public base { public: void myFunction() { cout<<"I'm inside derivedTwo's myFunction()\n"; } }; int main() { base bob; bob.myFunction(); derivedOne doob; doob.myFunction(); derivedTwo dtob; dtob.myFunction(); return 0; }
As you can see in the preceding example, I used the same method name in all three classes; the first is the base class, and the second and third are derived from it. The method "myFunction()" is overridden by the second and third classes. You can see that I used the same method with different forms in the preceding example. That is, each of the three methods prints different text on the output console.
Polymorphism also includes function overloading and operator overloading.
« Previous Tutorial Next Tutorial »