#OOPs Concepts in C++
Posted by Superadmin on December 25 2020 05:05:22
OOPs Concepts in C++
Object oriented programming is a way of solving complex problems by breaking them into smaller problems using objects. Before Object Oriented Programming (commonly referred as OOP), programs were written in procedural language, they were nothing but a long list of instructions. On the other hand, the OOP is all about creating objects that can interact with each other, this makes it easier to develop programs in OOP as we can understand the relationship between them.
Object Oriented Programming(OOP)
In Object oriented programming we write programs using classes and objects utilising features of OOPs such as abstraction, encapsulation, inheritance and polymorphism
Class and Objects
A class is like a blueprint of data member and functions and object is an instance of class. For example, lets say we have a class Car which has data members (variables) such as speed, weight, price and functions such as gearChange(), slowDown(), brake() etc. Now lets say I create a object of this class named FordFigo which uses these data members and functions and give them its own values. Similarly we can create as many objects as we want using the blueprint(class).
//Class name is Car
class Car
{
//Data members
char name[20];
int speed;
int weight;
public:
//Functions
void brake(){
}
void slowDown(){
}
};
int main()
{
//ford is an object
Car ford;
}
Abstraction
Abstraction is a process of hiding irrelevant details from user. For example, When you send an sms you just type the message, select the contact and click send, the phone shows you that the message has been sent, what actually happens in background when you click send is hidden from you as it is not relevant to you.
Encapsulation
Encapsulation is a process of combining data and function into a single unit like capsule. This is to avoid the access of private data members from outside the class. To achieve encapsulation, we make all data members of class private and create public functions, using them we can get the values from these data members or set the value to these data members.
Inheritance
Inheritance is a feature using which an object of child class acquires the properties of parent class.
#include <iostream>
using namespace std;
class ParentClass {
//data member
public:
int var1 =100;
};
class ChildClass: public ParentClass {
public:
int var2 = 500;
};
int main(void) {
ChildClass obj;
}
Now this object obj can use the properties (such as variable var1) of ParentClass.
Polymorphism
Function overloading and Operator overloading are examples of polymorphism. Polymorphism is a feature using which an object behaves differently in different situation.
In function overloading we can have more than one function with same name but different numbers, type or sequence of arguments.
Polymorphism Example
#include <iostream>
using namespace std;
class Sum {
public:
int add(int num1,int num2){
return num1 + num2;
}
int add(int num1, int num2, int num3){
return num1 + num2 + num3;
}
};
int main(void) {
//Object of class Sum
Sum obj;
//This will call the second add function
cout<<obj.add(10, 20, 30)<<endl;
//This will call the first add function
cout<<obj.add(11, 22);
return 0;
}
Output:
60
33
Constructors in C++
BY CHAITANYA SINGH | FILED UNDER: LEARN C++
Constructor is a special member function of a class that initializes the object of the class. Constructor name is same as class name and it doesn’t have a return type. Lets take a simple example to understand the working of constructor.
Simple Example: How to use constructor in C++
Read the comments in the following program to understand each part of the program.
#include <iostream>
using namespace std;
class constructorDemo{
public:
int num;
char ch;
/* This is a default constructor of the
* class, do note that it's name is same as
* class name and it doesn't have return type.
*/
constructorDemo() {
num = 100; ch = 'A';
}
};
int main(){
/* This is how we create the object of class,
* I have given the object name as obj, you can
* give any name, just remember the syntax:
* class_name object_name;
*/
constructorDemo obj;
/* This is how we access data members using object
* we are just checking that the value we have
* initialized in constructor are reflecting or not.
*/
cout<<"num: "<<obj.num<<endl;
cout<<"ch: "<<obj.ch;
return 0;
}
Output:
num: 100
ch: A
Constructor vs Member function
Now that we know what is constructor, lets discuss how a constructor is different from member function of the class.
1) Constructor doesn’t have a return type. Member function has a return type.
2) Constructor is automatically called when we create the object of the class. Member function needs to be called explicitly using object of class.
3) When we do not create any constructor in our class, C++ compiler generates a default constructor and insert it into our code. The same does not apply to member functions.
This is how a compiler generated default constructor looks:
class XYZ
{
....
XYZ()
{
//Empty no code
}
};
Types of Constructor in C++
There are two types of constructor in C++. 1) Default constructor 2) Parameterized constructor
1) Default Constructor
A default constructor doesn’t have any arguments (or parameters)
#include <iostream>
using namespace std;
class Website{
public:
//Default constructor
Website() {
cout<<"Welcome to BeginnersBook"<<endl;
}
};
int main(void){
/*creating two objects of class Website.
* This means that the default constructor
* should have been invoked twice.
*/
Website obj1;
Website obj2;
return 0;
}
Output:
Welcome to BeginnersBook
Welcome to BeginnersBook
When you don’t specify any constructor in the class, a default constructor with no code (empty body) would be inserted into your code by compiler.
2) Parameterized Constructor
Constructors with parameters are known as Parameterized constructors. These type of constructor allows us to pass arguments while object creation. Lets see how they look:
Lets say class name is XYZ
Default constructor:
XYZ() {
}
....
XYZ obj;
....
Parameterized Constructor:
XYZ(int a, int b) {
}
...
XYZ obj(10, 20);
Example:
#include <iostream>
using namespace std;
class Add{
public:
//Parameterized constructor
Add(int num1, int num2) {
cout<<(num1+num2)<<endl;
}
};
int main(void){
/* One way of creating object. Also
* known as implicit call to the
* constructor
*/
Add obj1(10, 20);
/* Another way of creating object. This
* is known as explicit calling the
* constructor.
*/
Add obj2 = Add(50, 60);
return 0;
}
Output:
30
110
Destructors in C++
BY CHAITANYA SINGH | FILED UNDER: LEARN C++
A destructor is a special member function that works just opposite to constructor, unlike constructors that are used for initializing an object, destructors destroy (or delete) the object.
Syntax of Destructor
~class_name()
{
//Some code
}
Similar to constructor, the destructor name should exactly match with the class name. A destructor declaration should always begin with the tilde(~) symbol as shown in the syntax above.
When does the destructor get called?
A destructor is automatically called when:
1) The program finished execution.
2) When a scope (the { } parenthesis) containing local variable ends.
3) When you call the delete operator.
Destructor Example
#include <iostream>
using namespace std;
class HelloWorld{
public:
//Constructor
HelloWorld(){
cout<<"Constructor is called"<<endl;
}
//Destructor
~HelloWorld(){
cout<<"Destructor is called"<<endl;
}
//Member function
void display(){
cout<<"Hello World!"<<endl;
}
};
int main(){
//Object created
HelloWorld obj;
//Member function called
obj.display();
return 0;
}
Output:
Constructor is called
Hello World!
Destructor is called
Destructor rules
1) Name should begin with tilde sign(~) and must match class name.
2) There cannot be more than one destructor in a class.
3) Unlike constructors that can have parameters, destructors do not allow any parameter.
4) They do not have any return type, just like constructors.
5) When you do not specify any destructor in a class, compiler generates a default destructor and inserts it into your code.
Structures in C++
BY CHAITANYA SINGH | FILED UNDER: LEARN C++
Structure is a compound data type that contains different variables of different types. For example, you want to store Student details like student name, student roll num, student age. You have two ways to do it, one way is to create different variables for each data, but the downfall of this approach is that if you want to store the details of multiple students, in that case it is not feasible to create separate set of variables for each student.
The second and best way of doing it by creating a structure like this:
struct Student
{
char stuName[30];
int stuRollNo;
int stuAge;
};
Now these three members combined will act like a separate variable and you can create structure variable like this:
structure_name variable_name
So if you want to hold the information of two students using this structure then you can do it like this:
Student s1, s2;
Then I can access the members of Student structure like this:
//Assigning name to first student
s1.stuName = "Ajeet";
//Assigning age to the second student
s2.stuAddr = 22;
Similarly I can set and get the values of other data members of the structure for every student. Lets see a complete example to put this up all together:
Structure Example in C++
#include <iostream>
using namespace std;
struct Student{
char stuName[30];
int stuRollNo;
int stuAge;
};
int main(){
Student s;
cout<<"Enter Student Name: ";
cin.getline(s.stuName, 30);
cout<<"ENter Student Roll No: ";
cin>>s.stuRollNo;
cout<<"Enter Student Age: ";
cin>>s.stuAge;
cout<<"Student Record:"<<endl;
cout<<"Name: "<<s.stuName<<endl;
cout<<"Roll No: "<<s.stuRollNo<<endl;
cout<<"Age: "<<s.stuAge;
return 0;
}
Output:
Enter Student Name: Negan
ENter Student Roll No: 4101003
Enter Student Age: 22
Student Record:
Name: Negan
Roll No: 4101003
Age: 22
Structure and Function in C++
BY CHAITANYA SINGH | FILED UNDER: LEARN C++
In this previous tutorial we learnt about structures, the compound data type that groups different types of variables. In this tutorial, we will learn how to pass structures as an argument to the function and how to return the structure from the function.
How to pass structure as an argument to function
Here we have a function printStudentInfo()
which takes structure Student
as an argument and prints the details of student using structure varaible. The important point to note here is that you should always declare the structure before function declarations, otherwise you will get compilation error.
#include <iostream>
using namespace std;
struct Student{
char stuName[30];
int stuRollNo;
int stuAge;
};
void printStudentInfo(Student);
int main(){
Student s;
cout<<"Enter Student Name: ";
cin.getline(s.stuName, 30);
cout<<"Enter Student Roll No: ";
cin>>s.stuRollNo;
cout<<"Enter Student Age: ";
cin>>s.stuAge;
printStudentInfo(s);
return 0;
}
void printStudentInfo(Student s){
cout<<"Student Record:"<<endl;
cout<<"Name: "<<s.stuName<<endl;
cout<<"Roll No: "<<s.stuRollNo<<endl;
cout<<"Age: "<<s.stuAge;
}
Output:
Enter Student Name: Rick
Enter Student Roll No: 666123
Enter Student Age: 19
Student Record:
Name: Rick
Roll No: 666123
Age: 19
How to return the Structure from a Function
In this example we have two functions one gets the values from user, assign them to structure members and returns the structure and the other function takes that structure as argument and print the details.
#include <iostream>
using namespace std;
struct Student{
char stuName[30];
int stuRollNo;
int stuAge;
};
Student getStudentInfo();
void printStudentInfo(Student);
int main(){
Student s;
s = getStudentInfo();
printStudentInfo(s);
return 0;
}
/* This function prompt the user to input student
* details, stores them in structure members
* and returns the structure
*/
Student getStudentInfo(){
Student s;
cout<<"Enter Student Name: ";
cin.getline(s.stuName, 30);
cout<<"Enter Student Roll No: ";
cin>>s.stuRollNo;
cout<<"Enter Student Age: ";
cin>>s.stuAge;
return s;
}
void printStudentInfo(Student s){
cout<<"Student Record:"<<endl;
cout<<"Name: "<<s.stuName<<endl;
cout<<"Roll No: "<<s.stuRollNo<<endl;
cout<<"Age: "<<s.stuAge;
}
Output:
Enter Student Name: Tyrion lannister
Enter Student Roll No: 333901
Enter Student Age: 39
Student Record:
Name: Tyrion lannister
Roll No: 333901
Age: 39
Enumeration in C++
BY CHAITANYA SINGH | FILED UNDER: LEARN C++
Enum is a user defined data type where we specify a set of values for a variable and the variable can only take one out of a small set of possible values. We use enum keyword to define a Enumeration.
enum direction {East, West, North, South}dir;
Here Enumeration name is direction which can only take one of the four specified values, the dir at the end of the declaration is an enum variable.
Lets take a simple example to understand this:
Here I have assigned the value West to the enum variable dir and when I displayed the value of dir it shows 1. This is because by default the values are in increasing order starting from 0, which means East is 0, West is 1, North is 2 and South is 3.
Simple enum Example
#include<iostream>
using namespace std;
enum direction {East, West, North, South}dir;
int main()
{
dir = West;
cout<<dir;
return 0;
}
Another way to declare enum variable
As we have seen in the above example that I have declared the enum variable dir during enum declaration, there is another way to declare an enum variable.
#include <iostream>
using namespace std;
enum direction {East, West, North, South};
int main(){
direction dir;
dir = South;
cout<<dir;
return 0;
}
Output:
3
Why use enum in C++
Now that we understand what is enum and how to use them in program, lets discuss why we use them:
Enums are used only when we expect the variable to have one of the possible set of values, for example, we have a dir variable that holds the direction. Since we have four directions, this variable can take any one of the four values, if we try to assign a another random value to this variable, it will throw a compilation error. This increases compile-time checking and avoid errors that occurs by passing in invalid constants.
Another important place where they are used frequently are switch case statements, where all the values that case blocks expect can be defined in an enum. This way we can ensure that the enum variable that we pass in switch parenthesis is not taking any random value that it shouldn’t accept.
How to change default values of Enum
#include <iostream>
using namespace std;
enum direction {East=11, West=22, North=33, South=44};
int main(){
direction dir;
dir = South;
cout<<dir;
return 0;
}
Output:
44
Inheritance in C++
BY CHAITANYA SINGH | FILED UNDER: LEARN C++
Inheritance is one of the feature of Object Oriented Programming System(OOPs), it allows the child class to acquire the properties (the data members) and functionality (the member functions) of parent class.
What is child class?
A class that inherits another class is known as child class, it is also known as derived class or subclass.
What is parent class?
The class that is being inherited by other class is known as parent class, super class or base class.
Syntax of Inheritance
class parent_class
{
//Body of parent class
};
class child_class : access_modifier parent_class
{
//Body of child class
};
What are the advantages of using inheritance in C++ Programming
The main advantages of inheritance are code reusability and readability. When child class inherits the properties and functionality of parent class, we need not to write the same code again in child class. This makes it easier to reuse the code, makes us write the less code and the code becomes much more readable.
Lets take a real life example to understand this: Lets assume that Human
is a class that has properties such as height, weight, colour etc and functionality such as eating(), sleeping(), dreaming(), working() etc.
Now we want to create Male
and Female
class, these classes are different but since both Male and Female are humans they share some common properties and behaviours (functionality) so they can inherit those properties and functionality from Human class and rest can be written in their class separately.
This approach makes us write less code as both the classes inherited several properties and functions from base class thus we didn’t need to re-write them. Also, this makes it easier to read the code.
Inheritance Example
Before we discuss the types of inheritance, lets take an example:
Here we have two classes Teacher
and MathTeacher
, the MathTeacher class inherits the Teacher class which means Teacher
is a parent class and MathTeacher
is a child class. The child class can use the property collegeName
of parent class.
Another important point to note is that when we create the object of child class it calls the constructor of child class and child class constructor automatically calls the constructor of base class.
#include <iostream>
using namespace std;
class Teacher {
public:
Teacher(){
cout<<"Hey Guys, I am a teacher"<<endl;
}
string collegeName = "Beginnersbook";
};
//This class inherits Teacher class
class MathTeacher: public Teacher {
public:
MathTeacher(){
cout<<"I am a Math Teacher"<<endl;
}
string mainSub = "Math";
string name = "Negan";
};
int main() {
MathTeacher obj;
cout<<"Name: "<<obj.name<<endl;
cout<<"College Name: "<<obj.collegeName<<endl;
cout<<"Main Subject: "<<obj.mainSub<<endl;
return 0;
}
Output:
Hey Guys, I am a teacher
I am a Math Teacher
Name: Negan
College Name: Beginnersbook
Main Subject: Math
Types of Inheritance in C++
1) Single inheritance
2) Multilevel inheritance
3) Multiple inheritance
4) Hierarchical inheritance
5) Hybrid inheritance
Single inheritance
In Single inheritance one class inherits one class exactly.
For example: Lets say we have class A and B
B inherits A
Example of Single inheritance:
#include <iostream>
using namespace std;
class A {
public:
A(){
cout<<"Constructor of A class"<<endl;
}
};
class B: public A {
public:
B(){
cout<<"Constructor of B class";
}
};
int main() {
//Creating object of class B
B obj;
return 0;
}
Output:
Constructor of A class
Constructor of B class
2)Multilevel Inheritance
In this type of inheritance one class inherits another child class.
C inherits B and B inherits A
Example of Multilevel inheritance:
#include <iostream>
using namespace std;
class A {
public:
A(){
cout<<"Constructor of A class"<<endl;
}
};
class B: public A {
public:
B(){
cout<<"Constructor of B class"<<endl;
}
};
class C: public B {
public:
C(){
cout<<"Constructor of C class"<<endl;
}
};
int main() {
//Creating object of class C
C obj;
return 0;
}
Output:
Constructor of A class
Constructor of B class
Constructor of C class
Multiple Inheritance
In multiple inheritance, a class can inherit more than one class. This means that in this type of inheritance a single child class can have multiple parent classes.
For example:
C inherits A and B both
Example of Multiple Inheritance:
#include <iostream>
using namespace std;
class A {
public:
A(){
cout<<"Constructor of A class"<<endl;
}
};
class B {
public:
B(){
cout<<"Constructor of B class"<<endl;
}
};
class C: public A, public B {
public:
C(){
cout<<"Constructor of C class"<<endl;
}
};
int main() {
//Creating object of class C
C obj;
return 0;
}
Constructor of A class
Constructor of B class
Constructor of C class
4)Hierarchical Inheritance
In this type of inheritance, one parent class has more than one child class. For example:
Class B and C inherits class A
Example of Hierarchical inheritance:
#include <iostream>
using namespace std;
class A {
public:
A(){
cout<<"Constructor of A class"<<endl;
}
};
class B: public A {
public:
B(){
cout<<"Constructor of B class"<<endl;
}
};
class C: public A{
public:
C(){
cout<<"Constructor of C class"<<endl;
}
};
int main() {
//Creating object of class C
C obj;
return 0;
}
Output:
Constructor of A class
Constructor of C class
5) Hybrid Inheritance
Hybrid inheritance is a combination of more than one type of inheritance. For example, A child and parent class relationship that follows multiple and hierarchical inheritance both can be called hybrid inheritance.
Polymorphism in C++
BY CHAITANYA SINGH | FILED UNDER: LEARN C++
Polymorphism is a feature of OOPs that allows the object to behave differently in different conditions. In C++ we have two types of polymorphism:
1) Compile time Polymorphism – This is also known as static (or early) binding.
2) Runtime Polymorphism – This is also known as dynamic (or late) binding.
1) Compile time Polymorphism
Function overloading and Operator overloading are perfect example of Compile time polymorphism.
Compile time Polymorphism Example
In this example, we have two functions with same name but different number of arguments. Based on how many parameters we pass during function call determines which function is to be called, this is why it is considered as an example of polymorphism because in different conditions the output is different. Since, the call is determined during compile time thats why it is called compile time polymorphism.
#include <iostream>
using namespace std;
class Add {
public:
int sum(int num1, int num2){
return num1+num2;
}
int sum(int num1, int num2, int num3){
return num1+num2+num3;
}
};
int main() {
Add obj;
//This will call the first function
cout<<"Output: "<<obj.sum(10, 20)<<endl;
//This will call the second function
cout<<"Output: "<<obj.sum(11, 22, 33);
return 0;
}
Output:
Output: 30
Output: 66
2) Runtime Polymorphism
Function overriding is an example of Runtime polymorphism.
Function Overriding: When child class declares a method, which is already present in the parent class then this is called function overriding, here child class overrides the parent class.
In case of function overriding we have two definitions of the same function, one is parent class and one in child class. The call to the function is determined at runtime to decide which definition of the function is to be called, thats the reason it is called runtime polymorphism.
Example of Runtime Polymorphism
#include <iostream>
using namespace std;
class A {
public:
void disp(){
cout<<"Super Class Function"<<endl;
}
};
class B: public A{
public:
void disp(){
cout<<"Sub Class Function";
}
};
int main() {
//Parent class object
A obj;
obj.disp();
//Child class object
B obj2;
obj2.disp();
return 0;
}
Output:
Super Class Function
Sub Class Function
Function overloading in C++
BY CHAITANYA SINGH | FILED UNDER: LEARN C++
Function overloading is a C++ programming feature that allows us to have more than one function having same name but different parameter list, when I say parameter list, it means the data type and sequence of the parameters, for example the parameters list of a function myfuncn(int a, float b)
is (int, float)
which is different from the function myfuncn(float a, int b)
parameter list (float, int)
. Function overloading is a compile-time polymorphism.
Now that we know what is parameter list lets see the rules of overloading: we can have following functions in the same scope.
sum(int num1, int num2)
sum(int num1, int num2, int num3)
sum(int num1, double num2)
The easiest way to remember this rule is that the parameters should qualify any one or more of the following conditions, they should have different type, number or sequence of parameters.
For example:
These two functions have different parameter type:
sum(int num1, int num2)
sum(double num1, double num2)
These two have different number of parameters:
sum(int num1, int num2)
sum(int num1, int num2, int num3)
These two have different sequence of parameters:
sum(int num1, double num2)
sum(double num1, int num2)
All of the above three cases are valid case of overloading. We can have any number of functions, just remember that the parameter list should be different. For example:
int sum(int, int)
double sum(int, int)
This is not allowed as the parameter list is same. Even though they have different return types, its not valid.
Function overloading Example
Lets take an example to understand function overloading in C++.
#include <iostream>
using namespace std;
class Addition {
public:
int sum(int num1,int num2) {
return num1+num2;
}
int sum(int num1,int num2, int num3) {
return num1+num2+num3;
}
};
int main(void) {
Addition obj;
cout<<obj.sum(20, 15)<<endl;
cout<<obj.sum(81, 100, 10);
return 0;
}
Output:
35
191
Function overloading Example 2
As I mentioned in the beginning of this guide that functions having different return types and same parameter list cannot be overloaded. However if the functions have different parameter list then they can have same or different return types to be eligible for overloading. In short the return type of a function
does not play any role in function overloading. All that matters is the parameter list of function.
#include <iostream>
using namespace std;
class DemoClass {
public:
int demoFunction(int i) {
return i;
}
double demoFunction(double d) {
return d;
}
};
int main(void) {
DemoClass obj;
cout<<obj.demoFunction(100)<<endl;
cout<<obj.demoFunction(5005.516);
return 0;
}
Output:
100
5006.52
Advantages of Function overloading
The main advantage of function overloading is to the improve the code readability and allows code reusability. In the example 1, we have seen how we were able to have more than one function for the same task(addition) with different parameters, this allowed us to add two integer numbers as well as three integer numbers, if we wanted we could have some more functions with same name and four or five arguments.
Imagine if we didn’t have function overloading, we either have the limitation to add only two integers or we had to write different name functions for the same task addition, this would reduce the code readability and reusability.
Function Overriding in C++
BY CHAITANYA SINGH | FILED UNDER: LEARN C++
Function overriding is a feature that allows us to have a same function in child class which is already present in the parent class. A child class inherits the data members and member functions of parent class, but when you want to override a functionality in the child class then you can use function overriding. It is like creating a new version of an old function, in the child class.
Function Overriding Example
To override a function you must have the same signature in child class. By signature I mean the data type and sequence of parameters. Here we don’t have any parameter in the parent function so we didn’t use any parameter in the child function.
#include <iostream>
using namespace std;
class BaseClass {
public:
void disp(){
cout<<"Function of Parent Class";
}
};
class DerivedClass: public BaseClass{
public:
void disp() {
cout<<"Function of Child Class";
}
};
int main() {
DerivedClass obj = DerivedClass();
obj.disp();
return 0;
}
Output:
Function of Child Class
Note: In function overriding, the function in parent class is called the overridden function and function in child class is called overriding function.
How to call overridden function from the child class
As we have seen above that when we make the call to function (involved in overriding), the child class function (overriding function) gets called. What if you want to call the overridden function by using the object of child class. You can do that by creating the child class object in such a way that the reference of parent class points to it. Lets take an example to understand it.
#include <iostream>
using namespace std;
class BaseClass {
public:
void disp(){
cout<<"Function of Parent Class";
}
};
class DerivedClass: public BaseClass{
public:
void disp() {
cout<<"Function of Child Class";
}
};
int main() {
/* Reference of base class pointing to
* the object of child class.
*/
BaseClass obj = DerivedClass();
obj.disp();
return 0;
}
Output:
Function of Parent Class
If you want to call the Overridden function from overriding function then you can do it like this:
parent_class_name::function_name
To do this in the above example, we can write following statement in the disp() function of child class:
BaseClass::disp();
Difference between Function Overloading and Function overriding in C++
BY CHAITANYA SINGH | FILED UNDER: LEARN C++
Function overloading and Function overriding both are examples of polymorphism but they are completely different. Before we discuss the difference between them, lets discuss a little bit about them first.
Function Overloading
Function overloading is a feature that allows us to have same function more than once in a program. Overloaded functions have same name but their signature must be different.
Example:
Here we have the same function sum declared four times with different signatures. Based on the parameters we pass, while calling function sum, decides which method is to be called. This happens during compilation, which is why it is also known as compile time polymorphism. If you are wondering why I have suffixed each floating point value with “f” letter in the example below, during function call then refer this: function overloading float issue.
#include <iostream>
using namespace std;
// overloaded functions
float sum(int, int);
float sum(float, float);
float sum(int, float);
float sum(float, int);
int main(){
//This will call the second function
cout<<sum(15.7f, 12.7f)<<endl;
//This will call the first function
cout<<sum(200, 100)<<endl;
//This will call the third function
cout<<sum(100, 20.7f)<<endl;
//This will call the fourth function
cout<<sum(90.8f, 30)<<endl;
return 0;
}
float sum(int a, int b){
return a+b;
}
float sum(float a, float b){
return a+b;
}
float sum(int a, float b){
return a+b;
}
float sum(float a, int b){
return a+b;
}
Output:
28.4
300
120.7
120.8
Function Overriding
Function overriding is a feature of OOPs Programming that allows us to override a function of parent class in child class.
Example:
#include<iostream>
using namespace std;
//Parent class or super class or base class
class A{
public:
void disp() {
cout<<"Parent Class disp() function"<<endl;
}
void xyz() {
cout<<"xyz() function of parent class";
}
};
//child class or sub class or derived class
class B : public A{
public:
/* Overriding disp() function of parent class
* and giving a different definition to it.
*/
void disp() {
cout<<"Child class disp() function"<<endl;
}
};
int main(){
//Creating object of child class B
B obj;
obj.disp();
/* If you want to call the overridden function
* (the same function which is present in parent class)
* from the child class then assign the reference of
* parent class to the child class object.
*/
A obj2 = B();
obj2.disp();
}
Output:
Child class disp() function
Parent Class disp() function
Difference between function overloading and function overriding
Now that we understand what is function overloading and overriding in C++ programming, lets see the difference between them:
1) Function Overloading happens in the same class when we declare same functions with different arguments in the same class. Function Overriding is happens in the child class when child class overrides parent class function.
2) In function overloading function signature should be different for all the overloaded functions. In function overriding the signature of both the functions (overriding function and overridden function) should be same.
3) Overloading happens at the compile time thats why it is also known as compile time polymorphism while overriding happens at run time which is why it is known as run time polymorphism.
4) In function overloading we can have any number of overloaded functions. In function overriding we can have only one overriding function in the child class.
Virtual functions in C++: Runtime Polymorphism
BY CHAITANYA SINGH | FILED UNDER: LEARN C++
In this guide, we will see what are virtual functions and why we use them. When we declare a function as virtual in a class, all the sub classes that override this function have their function implementation as virtual by default (whether they mark them virtual or not). Why we declare a function virtual? To let compiler know that the call to this function needs to be resolved at runtime (also known as late binding and dynamic linking) so that the object type is determined and the correct version of the function is called.
Lets take an example to understand what happens when we don’t mark a overridden function as virtual.
Example 1: Overriding a non-virtual function
See the problem here. Even though we have the parent class pointer pointing to the instance (object) of child class, the parent class version of the function is invoked.
You may be thinking why I have created the pointer, I could have simply created the object of child class like this: Dog obj; and assigned the Dog instance to it. Well, in this example I have only one child class but when we a big project having several child classes, creating the object of child class separately is not recommended as it increases the complexity and the code become error prone. More clarity to this after this example.
#include<iostream>
using namespace std;
//Parent class or super class or base class
class Animal{
public:
void animalSound(){
cout<<"This is a generic Function";
}
};
//child class or sub class or derived class
class Dog : public Animal{
public:
void animalSound(){
cout<<"Woof";
}
};
int main(){
Animal *obj;
obj = new Dog();
obj->animalSound();
return 0;
}
Output:
This is a generic Function
Example 2: Using Virtual Function
See in this case the output is Woof, which is what we expect. What happens in this case? Since we marked the function animalSound() as virtual, the call to the function is resolved at runtime, compiler determines the type of the object at runtime and calls the appropriate function.
#include<iostream>
using namespace std;
//Parent class or super class or base class
class Animal{
public:
virtual void animalSound(){
cout<<"This is a generic Function";
}
};
//child class or sub class or derived class
class Dog : public Animal{
public:
void animalSound(){
cout<<"Woof";
}
};
int main(){
Animal *obj;
obj = new Dog();
obj->animalSound();
return 0;
}
Output:
Woof
Encapsulation in C++ with example
BY CHAITANYA SINGH | FILED UNDER: LEARN C++
Encapsulation is a process of combining data members and functions in a single unit called class. This is to prevent the access to the data directly, the access to them is provided through the functions of the class. It is one of the popular feature of Object Oriented Programming(OOPs) that helps in data hiding.
How Encapsulation is achieved in a class
To do this:
1) Make all the data members private.
2) Create public setter and getter functions for each data member in such a way that the set function set the value of data member and get function get the value of data member.
Let’s see this in an example Program:
Encapsulation Example in C++
Here we have two data members num and ch, we have declared them as private so that they are not accessible outside the class, this way we are hiding the data. The only way to get and set the values of these data members is through the public getter and setter functions.
#include<iostream>
using namespace std;
class ExampleEncap{
private:
/* Since we have marked these data members private,
* any entity outside this class cannot access these
* data members directly, they have to use getter and
* setter functions.
*/
int num;
char ch;
public:
/* Getter functions to get the value of data members.
* Since these functions are public, they can be accessed
* outside the class, thus provide the access to data members
* through them
*/
int getNum() const {
return num;
}
char getCh() const {
return ch;
}
/* Setter functions, they are called for assigning the values
* to the private data members.
*/
void setNum(int num) {
this->num = num;
}
void setCh(char ch) {
this->ch = ch;
}
};
int main(){
ExampleEncap obj;
obj.setNum(100);
obj.setCh('A');
cout<<obj.getNum()<<endl;
cout<<obj.getCh()<<endl;
return 0;
}
Output:
100
A
Abstraction in C++ with example
BY CHAITANYA SINGH | FILED UNDER: LEARN C++
Abstraction is one of the feature of Object Oriented Programming, where you show only relevant details to the user and hide irrelevant details. For example, when you send an email to someone you just click send and you get the success message, what actually happens when you click send, how data is transmitted over network to the recipient is hidden from you (because it is irrelevant to you).
Let’s see how this can be achieved in a C++ program using access specifiers:
Abstraction Example
#include <iostream>
using namespace std;
class AbstractionExample{
private:
/* By making these data members private, I have
* hidden them from outside world.
* These data members are not accessible outside
* the class. The only way to set and get their
* values is through the public functions.
*/
int num;
char ch;
public:
void setMyValues(int n, char c) {
num = n; ch = c;
}
void getMyValues() {
cout<<"Numbers is: "<<num<< endl;
cout<<"Char is: "<<ch<<endl;
}
};
int main(){
AbstractionExample obj;
obj.setMyValues(100, 'X');
obj.getMyValues();
return 0;
}
Output:
Numbers is: 100
Char is: X
Advantage of data abstraction
The major advantage of using this feature is that when the code evolves and you need to make some adjustments in the code then you only need to modify the high level class where you have declared the members as private. Since none class is accessing these data members directly, you do not need to change the low level(user level) class code.
Imagine if you had made these data members public, if at some point you want to change the code, you would have to make the necessary adjustments to all the classes that are accessing the members directly.
Other advantages of data abstraction are:
1) Makes the application secure by making data private and avoiding the user level error that may corrupt the data.
2) This avoids code duplication and increases the code reusability.
Interfaces in C++: Abstract Class
BY CHAITANYA SINGH | FILED UNDER: LEARN C++
In C++, we use terms abstract class and interface interchangeably. A class with pure virtual function is known as abstract class. For example the following function is a pure virtual function:
virtual void fun() = 0;
A pure virtual function is marked with a virtual keyword and has = 0
after its signature. You can call this function an abstract function as it has no body. The derived class must give the implementation to all the pure virtual functions of parent class else it will become abstract class by default.
Why we need a abstract class?
Let’s understand this with the help of a real life example. Lets say we have a class Animal
, animal sleeps, animal make sound, etc. For now I am considering only these two behaviours and creating a class Animal with two functions sound()
and sleeping()
.
Now, we know that animal sounds are different cat says “meow”, dog says “woof”. So what implementation do I give in Animal
class for the function sound()
, the only and correct way of doing this would be making this function pure abstract so that I need not give implementation in Animal class but all the classes that inherits Animal class must give implementation to this function. This way I am ensuring that all the Animals have sound but they have their unique sound.
The same example can be written in a C++ program like this:
Abstract class Example
#include<iostream>
using namespace std;
class Animal{
public:
//Pure Virtual Function
virtual void sound() = 0;
//Normal member Function
void sleeping() {
cout<<"Sleeping";
}
};
class Dog: public Animal{
public:
void sound() {
cout<<"Woof"<<endl;
}
};
int main(){
Dog obj;
obj.sound();
obj.sleeping();
return 0;
}
Rules of Abstract Class
1) As we have seen that any class that has a pure virtual function is an abstract class.
2) We cannot create the instance of abstract class. For example: If I have written this line Animal obj;
in the above program, it would have caused compilation error.
3) We can create pointer and reference of base abstract class points to the instance of child class. For example, this is valid:
Animal *obj = new Dog();
obj->sound();
4) Abstract class can have constructors.
5) If the derived class does not implement the pure virtual function of parent class then the derived class becomes abstract.
Friend Class and Friend Functions in C++
BY CHAITANYA SINGH | FILED UNDER: LEARN C++
As we know that a class cannot access the private members of other class. Similarly a class that doesn’t inherit another class cannot access its protected members.
Friend Class:
A friend class is a class that can access the private and protected members of a class in which it is declared as friend. This is needed when we want to allow a particular class to access the private and protected members of a class.
Function Class Example
In this example we have two classes XYZ
and ABC
. The XYZ
class has two private data members ch
and num
, this class declares ABC
as friend class. This means that ABC
can access the private members of XYZ
, the same has been demonstrated in the example where the function disp()
of ABC
class accesses the private members num
and ch
. In this example we are passing object as an argument to the function.
#include <iostream>
using namespace std;
class XYZ {
private:
char ch='A';
int num = 11;
public:
/* This statement would make class ABC
* a friend class of XYZ, this means that
* ABC can access the private and protected
* members of XYZ class.
*/
friend class ABC;
};
class ABC {
public:
void disp(XYZ obj){
cout<<obj.ch<<endl;
cout<<obj.num<<endl;
}
};
int main() {
ABC obj;
XYZ obj2;
obj.disp(obj2);
return 0;
}
Output:
A
11
Friend Function:
Similar to friend class, this function can access the private and protected members of another class. A global function can also be declared as friend as shown in the example below:
Friend Function Example
#include <iostream>
using namespace std;
class XYZ {
private:
int num=100;
char ch='Z';
public:
friend void disp(XYZ obj);
};
//Global Function
void disp(XYZ obj){
cout<<obj.num<<endl;
cout<<obj.ch<<endl;
}
int main() {
XYZ obj;
disp(obj);
return 0;
}
Output:
100
Z