Category: CPlusPlus Tutorial

  • C++ Templates

    Templates in C++ are the powerful feature that allows us to write generic programs (generic classes and generic functions).

    A single class or function is created to work with different data types using templates. We pass the data types in a function as a parameter so that repetition of the same code can be avoided for different data types.

    The passed parameter is called the template parameter. It is the same as the regular parameter but here instead of values we pass different data types.

    The templates can be represented in two different ways.

    • Function Templates
    • Class Templates
    templates in C++

    Function Templates

    We can create the function template in order to use it for different data types such as float, int, double, etc. For example, suppose we create a function called mul() for the multiplication, in normal function this function is used for specific data-types values but with templates we can pass any data types into the function.

    It makes a better approach because we can write less code and save time from the repetition of writing code that is used to do the same work.

    Syntax of Function Template:

    template <class T> T func_name(T parameter_list) 
    {
       // body of function
    } 
    • T is a template argument or placeholder name for a data type (int, float, etc). The compiler automatically replaces it with the actual data type.
    • class is a keyword used for generic type and it can replace with typename.

    Example of function templates in C++

    #include <iostream>  
    using namespace std; 
    
    template<class T> T mul(T &num1,T &num2)  
    {  
        T product = num1 + num2;  
        return product;  
    }  
    
    int main()  
    {  
      int a = 4, b = 2;  
      float x = 3.3, y = 2.3;  
      
      cout<<"Multiplication of a and b: "<< mul(a,b) << endl;
      cout<<"Multiplication of x and y: "<< mul(x,y);  
      return 0;  
    }  

    Output:

    Multiplication of a and b: 6
    Multiplication of x and y: 5.6

    Class Templates

    Just like a function template, we can create a template for the class for generic operations that is independent of any data type.

    It is required when we need the same implementation for many classes but for different data types and also avoided repetition of the same code.

    Syntax of class Template:

    template<class T> class class_name   
    {
       ....
       ....
       ......
    } 

    Creating class template object.

    The data type is mentioned inside <> while creating an object for the class template. For example:

    //Syntax
    class_name<dataType> classObject;
    
    //Example
    class_name<int> classObject;
    class_name<float> classObject;

    let us go through an example of a class template in C++ to understand more.

    Example of class templates in C++

    #include <iostream>
    using namespace std;
    
    template <class T>
    class Operation
    {
        public:
            T num1 = 10.5, num2 = 5.2;
    
        	void print()
        	{
        		cout << "Addition: " << add() << endl;
        		cout << "Subtraction: " << sub() << endl;
        		cout << "Product: " << mul() << endl;
        		cout << "Division: " << divide() << endl;
        	}
        	
        	T add() { 
        	    return num1 + num2; 
        	    
        	}
        	T sub() { 
        	    return num1 - num2; 
        	    
        	}
        	T mul() { 
        	    return num1 * num2; 
        	    
        	}
        	T divide() { 
        	    return num1 / num2; 
        	    
        	}
    };
    
    int main()
    {
    	Operation<int> intOb;
    	Operation<float> floatOb;
    	
    	cout << "INTEGER:" << endl;
    	intOb.print();
    	
    	cout << endl << "FLOAT:" << endl;
    	floatOb.print();
    	
    	return 0;
    }

    Output:

    INTEGER:
    Addition: 15
    Subtraction: 5
    Product: 50
    Division: 2
    
    FLOAT:
    Addition: 15.7
    Subtraction: 5.3
    Product: 54.6
    Division: 2.01923

    As you can see that the result is shown according to the data type passed while creating class objects (intOb, floatOb).


  • C++ Friend Function

    There are private and protected members in a class that is inaccessible from outside of the class, constituting one of the concepts of object-oriented programming i.e. data hiding. However, these rules can be broken by a friend function.

    A function defined with a friend keyword is called a friend function. It can access both the private and protected members from outside the class.

    Declaration of friend function:

    class class_name    
    {    
        .......
        friend data_type function_name(arguments);
    
        .......
    };   
    • A friend can be a member’s function, function template, or function, or a class or class template,  in which case the entire class and all of its members are friends.
    • Although the friend function appears inside the class, they are not membersfunction.
    • They can be declared anywhere in the class.

    Example: C++ program for a friend function

    #include <iostream>    
    using namespace std;    
    class Number    
    {    
        private:    
            int num;    
        public:    
            Number(): num(0) { }    
            friend int add(Number); //friend function    
    };    
    int add(Number n)    
    {    
       n.num += 20;    
        return n.num;    
    }    
    int main()    
    {    
        Number num;    
        cout<<"Number: "<< add(num)<<endl;    
        return 0;    
    }   

    Output:

    Number: 20

    C++ friend class

    friend keyword is also used to declare a friend class in C++. When a class is declared a friend class, all the member functions of the friend class become friend functions.

    class Two;
    
    class One {
       // class Two is a friend class of class One
       friend class Two;
       ... .. ...
    }
    
    class Two{
       ... .. ...
    }

    In the above example, class Two is a friend class of class One indicating that we can access all the members of class One from class Two. However, vice-versa is not granted.

    Example: C++ program for a friend class.

    #include <iostream>  
    using namespace std;  
      
    class One  
    {  
        int num = 10;  
        friend class Two; // friend class.  
    };  
    
    class Two  
    {  
      public:  
        void print(One &o)  
        {  
            cout<<"Num = "<<o.num;  
        }  
    };  
    int main()  
    {  
        One o;  
        Two t;  
        t.print(o);  
        return 0;  
    }  

    Output:

    Num = 10

  • this Pointer in C++

    In C++, this is a keyword that refers to the current instance of a class and this pointer holds the address or points to the current object of the class. Also, only the member functions have this pointer.

    Members like friend functions do not have this pointer as they are not members of the class.

    Example of this pointer in C++

    Let us see an example of C++ this pointer that refers to the fields of the current class.

    #include <iostream>  
    using namespace std; 
    
    class Student 
    {  
       public:  
           int roll; //fields      
           string name;  
           float score;
           
           Student(int roll, string name, float score)    
           {    
               this->roll = roll;    
               this->name = name;    
               this->score = score;   
           }    
           void print()    
            {    
               cout << "Roll No: " << roll << endl;    
               cout << "Name: " << name << endl;    
               cout << "Score: " << score << endl << endl;    
            }    
    };  
    
    int main(void) 
    {  
        //creating Object
        Student s1 = Student(1101, "John", 80);  
        Student s2 = Student(1102, "Emma", 95); 
        
        s1.print();    
        s2.print();    
        
        return 0;  
    }  

    Output:

    Roll No: 1101
    Name: John
    Score: 80


    Roll No: 1102
    Name: Emma
    Score: 95


  • Inheritance in C++

    Inheritance is one of the most important concepts of object-oriented programming. In C++, inheritance is the process of deriving the properties and behaviors of one class to another class. It is like a child and parent where the child possesses the properties of the parent.

    • The class which inherits the members of another class is called the derived class (child/sub).
    • The class whose members are inherited is called the base class (super/parent).

    Importance of Inheritance:

    • For Code Reusability.
    • For Method Overriding (to achieve runtime polymorphism).

    A basic example of Inheritance.

    class Animal 
    {
        // eat() function
        // sleep() function
    };
    
    class Cat: public Animal 
    {
        // sound() function
    };

    As you can see in the above example Cat class inherits from the Animal class which means that the Cat class has can access the eat() and sleep() methods of Animal and also has its own additional method sound().

    Modes of Inheritance.

    It is the visibility mode that is used while deriving a parent class. such as:

    class derived_class_name : visibility-mode parent_class_name  
    {  
        // derived class members.  
    }  

    We can derive the parent class publicly or privately.

    Public mode: When the derive class publicly inherits the base class then the public members of the base class also become the public members of the derived class. Therefore, the public members of the base class are accessible by the objects of the derived class as well as by the member functions of the base class.

    Private mode: When the derive class privately inherits the base class then the public members of the base class become the private members of the derived class.


    Types Of Inheritance

    C++ supports the following five types of inheritance.

    1. Single inheritance
    2. Multiple inheritance
    3. Multilevel inheritance
    4. Hierarchical inheritance
    5. Hybrid inheritance

    1. Single Inheritance

    It refers to an inheritance where a child inherits a single-parent class.
    In the diagram below, class B inherits class A.

    single Inheritance

    Syntax:

    class subclass_name : access_mode base_class_name
    {
      //body of subclass
    };

    Example: C++ example for single inheritance.

    #include <iostream>  
    using namespace std; 
    
    class One  
    {  
        public:  
            int num1 = 10;  
            int num2 = 20; 
            
            int add()  
            {  
              int sum = num1 + num2;  
              return sum;  
            }     
    };  
      
    class Two : public One  
    {  
        public:  
            void print()  
            {  
              //Inheriting method
              int result = add();  
              cout <<"Result of addition: "<< result << endl;  
            }  
    };  
    
    int main()  
    {  
       Two two;  
       //Inheriting Field
       cout << two.num1 << endl;
       two.print();  
      
        return 0;  
    }  

    Output:

    10
    Result of addition: 30


    2. Multiple Inheritance

    Multiple inheritance is the process where the single class inherits the properties from two or more classes.

    In the diagram below, class C inherits from both Class A and Class B.

    multiple Inheritance

    Syntax:

    class subclass_name : specifier base_class1, specifier base_class2, ....
    {
      //body of subclass
    };

    Example: C++ example for multiple inheritance.

    #include <iostream>  
    using namespace std;  
    
    class One  
    {  
        protected:  
            int num1;  
        public:  
            void getNum1(int n)  
            {  
                num1 = n;  
            }  
    };  
      
    class Two  
    {  
        protected:  
            int num2;  
        public:  
            void getNum2(int n)  
            {  
                num2 = n;  
            }  
    };  
    
    //Inherits from One and Two
    class Three : public One, public Two  
    {  
       public:  
         void print()  
         {  
            int sum = num1 + num2;
            cout << "num1 : " << num1 << endl;  
            cout << "num2 : " << num2 << endl;  
            cout << "Result of sum: " << sum;  
         }  
    };  
    int main()  
    {  
       Three th;  
       th.getNum1(5);  
       th.getNum2(10);  
       th.print();  
      
        return 0;  
    }  

    Output:

    num1 : 5
    num2 : 10
    Result of sum: 15


    3. Multilevel Inheritance

    In this type inheritance derived class is created from another derived class. In multilevel inheritance, one class inherits from another class which is further inherited by another class. The last derived class possesses all the members of the above base classes.

    Multilevel Inheritance

    Example: C++ example for multilevel inheritance.

    #include <iostream>  
    using namespace std;  
    
    class Animal 
    {  
       public:  
          void sleep() 
          {   
            cout<<"Animal sleep"<<endl;   
          }    
       }; 
       
    class Dog: public Animal   
    {    
       public:  
          void bark()
          {  
            cout<<"Dog Barking"<<endl;   
          }    
    };
    
    class Puppy: public Dog   
    {    
       public:  
          void puppies() 
          {  
            cout<<"Puppies";   
          }    
     };  
     
    int main(void) 
    {  
        Puppy d;  
        d.sleep();  
        d.bark();  
        d.puppies();
         
         return 0;  
    }  

    Output:

    Animal sleep
    Dog Barking
    Puppies


    4. Hierarchical Inheritance

    The process of deriving more than one class from a base class is called hierarchical inheritance. In other words, we create more than one derived class from a single base class.

    hierarchical Inheritance

    Syntax:

    class One  
    {  
        // Class One members  
    }    
    class Two : public One   
    {  
        // Class Two members.  
    }  
    class Three : public One  
    {  
        // Class Three members  
    }   
    class Four : public One   
    {  
        // Class Four members  
    }  

    Example: C++ example for hierarchical Inheritance.

    #include <iostream>  
    using namespace std;  
    
    class Animal 
    {  
       public:  
          void sleep() 
          {   
            cout<<"Animal sleep"<<endl;   
          }    
       }; 
       
    class Dog: public Animal   
    {    
       public:  
          void dogSound()
          {  
            cout<< "Barks" <<endl;   
          }    
    };
    
    class Cat: public Animal   
    {    
       public:  
          void catSound() 
          {  
            cout<< "Meow" << endl;   
          }    
     };  
     
    int main(void) 
    {  
        Cat c;  
        c.sleep();  
        c.catSound();  
        Dog d;  
        d.sleep();  
        d.dogSound();
         
         return 0;  
    }  

    Output:

    Animal sleep
    Meow

    Animal sleep
    Barks


    5. Hybrid (Virtual) Inheritance

    Hybrid inheritance is the combination of more than one type of inheritance. In the diagram below is the combination of hierarchical Inheritanceand multiple inheritance.

    hybrid Inheritance

    Example: C++ example for hierarchical Inheritance.

    #include <iostream>  
    using namespace std; 
    
    class One 
    {  
        protected:  
            int a = 20;  
        public:  
            void getOne()  
            {  
               cout << "Value of a: " << a <<endl;   
            }  
    };  
    
    class Two   
    {  
        protected:  
            int b = 30;  
        public:  
            void getTwo()  
            {  
                cout << "Value of b: " << b <<endl;
            }  
    };
      
    class Three : public One   
    {  
        protected:  
            int c = 50;  
        public:  
            void getThree()  
            {  
                cout << "Value of c: " << c <<endl;  
            }  
    };  
      
      
    class Four : public Two, public Three  
    {  
        protected:  
           int d;  
           
        public:  
            void add()  
            {  
              getOne();  
              getTwo();  
              getThree();  
              cout << "Sum : " << a + b + c;  
            }  
    };  
    int main()  
    {  
        Four fr;  
        fr.add();  
        return 0;  
    }  

    Output:

    Value of a: 20
    Value of b: 30
    Value of c: 50
    Sum : 100


    Ambiguity in Inheritance

    When there is a function present with the same name in two or more base classes then during multiple inheritances or single inheritance an ambiguity can occur in such cases.

    Example: C++ example for ambiguity in multiple inheritance.

    #include <iostream>  
    using namespace std; 
    
    class One 
    {   
        public:  
            void display()  
            {  
               cout << "Class One" << endl;   
            }  
    };  
    
    class Two   
    {   
        public:  
            void display()  
            {  
                cout << "Class Two" << endl;
            }  
    };
      
    class Three : public One, public Two   
    {   
        public:  
            void print()  
            {  
                display();
            }  
    };  
      
    int main()  
    {  
        Three th;  
        th.print(); 
        
        return 0;  
    }  

    There are display() functions in both the classes of One and Two. The following error will be displayed after execution.

    error: reference to ‘display’ is ambiguous
             display();

    To overcome this problem we need to do the following changes in Class Three by using the class resolution operator (::).

    class Three : public One, public Two   
    {   
        public:  
            void print()  
            {  
                One :: display(); 
                Two :: display();
            }  
    }; 

  • C++ Encapsulation

    Encapsulation is defined as the wrapping up of data(variable) under a single unit. Encapsulation is an important concept of OOP in C++ that binds data and functions inside a class together that manipulate them. Data encapsulation leads to the important concept called data hiding.

    It makes sure that the ‘sensitive’ data are hidden from the user and an access specifier is used to achieve this. private specifier is used to hide sensitive data, it makes the data inaccessible from outside the class. But to modify or read those data, we need to use the getter and setter (i.e. get and set) method. It prevents from accessing the data directly.

    Example of specifiers to bind data:

    class Square
    {
       private:
          double side;  
    
    
       public:
          void setSide(int s) 
          {
            if (s >= 0)
             side = s;
          }
    };

    Let us go through an example in C++ to understand the concept of hiding data.


    Data Hiding Using the private Specifier in C++

    #include <iostream>
    using namespace std;
    
    class Rectangle 
    {
       //private members
       private:
          float length;
          float breadth;
    
       public:
    
         // Setter for length and breadth
         void setLength(float l) 
         {
           length = l;
         }
         void setBreadth(float b) 
         {
           breadth = b;
         }
    
         // Getter for length and breadth
         float getLength() 
         {
           return length;
         }
         float getBreadth() 
         {
           return breadth;
         }
        
         // area function
         float getArea() 
         {
           return length * breadth;
         }
    };
    
    //main function
    int main() 
    {
      Rectangle rect;
    
      //setting the length and breadth value
      rect.setLength(10);
      rect.setBreadth(6.5);
    
      // getting the length and breadth value
      float length = rect.getLength();
      cout << "Length: " << length << endl;
    
      float breadth = rect.getBreadth();
      cout << "Breadth: " << breadth << endl;
    
      // Area
      cout << "Area of a rectangle: " << rect.getArea();
    
      return 0;
    }

    Output:

    Length: 10
    Breadth: 6.5
    Area of a rectangle: 65

    In the above program length and breadth in Rectangle class is a private member which means they are not accessible from outside the class. So to get and set the value of length and breadth, we created a setter (pass the value) and getter (return the value). Hence the private members are not accessible directly, making it hidden.


    Benefits of Encapsulation:

    • Data- hiding in Java.
    • The class field can be made read-only or write-only.
    • It provides the class the total control over the data.

  • C++ Interface (Abstract classes)

    The interface is implemented using an abstract class in C++, hence the word interface and abstract class are used interchangeably.

    Abstraction classes are the way to achieve abstraction and abstraction is a technique in programming to hide the internal details and only show the necessary functionalities.

    The classes with at least one pure virtual function are said to be abstract classes. A pure virtual function is has a signature as “0” and of course with a virtual keyword itself as shown below.

    virtual void fun() = 0;

    And the above function can be called an abstract function as it has no body. The purpose of an abstract class is to serve as an interface and provide a base class from which other classes can inherit. Also, the instance of an abstract class cannot be created.

    Let us understand through an example in C++ for abstract classes.


    C++ Abstract class example

    In the program below, we have three classes Animal (parent class), Cat, and Dog (derived class). The sound() function for each animal (dog and cat) is different but they have the same function name, so the function sound() is made pure virtual function in the parent class, Animal.

    #include <iostream>
    using namespace std;
    
    class Animal
    {
       public:
         //Pure Virtual Function
         virtual void sound() = 0;
    
         //Parent member Function
         void eat()
         {
           cout << "Animals eat.";
         }
    };
    
    //Cat class inherits Animal
    class Cat: public Animal
    {
       public:
         void sound()
         {
            cout << "Meow" << endl;
         }
    };
    
    //Dog class inherits Animal
    class Dog: public Animal
    {
       public:
         void sound()
         {
           cout << "Woof" << endl;
         }
    };
    
    //main function
    int main()
    {
       Dog d;
       Cat c;
    
       d.sound();
       c.sound();
       d.eat();
    
       return 0;
    }

    Output:

    Woof
    Meow
    Animals eat.


  • C++ Data Abstraction

    Data abstraction is the process of hiding the details but only displaying the relevant information to the users. This is one of the main advantages of using abstraction.

    It is a programming way or a technique through which we can separate the interface with the implementation details.

    Take a real-life example:
    Suppose a person is typing with the help of a keyboard on his/her computer. That person knows that pressing any alphabet on the keyboard, displays that alphabet on the screen of the monitor but he/she doesn’t know how the internal mechanism is working to display the alphabet.
    Therefore, hiding the internal mechanism and showing only its output is an abstraction in this example.

    C++ also provides a great level of abstraction such as the function pow() we use in a program to calculate the power of some number is internally implemented. Although we do not know how it is implemented. We just use it by calling pow() without knowing its algorithm.

    There is another example such as private and public modifiers or sort()function that we use in a program.

    In C++, abstraction can be achieved in two ways.

    • Abstraction using classes
    • Abstraction in header files.

    Abstraction using Classes:

    Classes are used o achieve abstraction in C++. A class grouped the class members that is data members and member function into a single unit using access specifiers. A class can decide which members are relevant to show to the outside world and which to hide.

    Abstraction in Header files:

    Another way to achieve abstraction is through header files. For example, consider the use of function pow() in a program to calculate the power of some number that is present in math.h header file, and this function is internally implemented. Although we do not know how it is implemented. We just use it by calling pow() without knowing its algorithm.

    Access Specifiers for abstraction:

    Access specifiers are the main way to implement abstraction and enforce the restriction on class members in C++.

    • private: The members declared private are only accessible to the class They are not allowed to access outside the class, hence making it secure.
    • public: The members declared public can be accessed from anywhere in the program.

    Let us understand through a C++ example for abstraction using the above two specifiers.

    Example of C++ data abstraction using classes

    //C++ program to demonstrate the abstraction
    
    #include <iostream>
    using namespace std;
    
    class Average
    {
       // delaring private members 
       private:
          int num1, num2, avg;
    
       // public members 
       public_colon
       void set(int x, int y)
       {
          num1 = x;
          num2 = y;
       }
    
       void display()
       {
          avg = (num1 + num2) / 2;
          cout << "Average: " << avg << endl;
       }
    };
    
    int main()
    {
       Average ag;
    
       ag.set(10, 10);
       ag.display();
    
       return 0;
    }

    Output:

    Average: 10

    As you can see in the above program the private variables num1, num2 and avg cannot be accessed outside the class. Only the public member functions are allowed to access.


    Advantage of data abstraction

    • When you need to modify the code in the future, you only need to modify the higher-level class and no need to modify the lower-level class.
    • It also avoids code duplication increases the reusability of the code.
    • Since the abstraction separates the interface and implementation, the internal changes can be easily made without affecting the user-level code.
    • The abstracting of the data itself increases the security as no user can access the internal hidden mechanism.

  • C++ Virtual Function

    Virtual function in C++ is a member function in the base class that we redefined in a derived class. With the use of a virtual function, we ensure that the function is overridden.

    A virtual function lets the compiler know to perform dynamic linkage or late binding on the function (that is the called function needs to be resolved at run time).

    A keyword ‘virtual‘ is used preceding with the function to be overridden. A virtual function cannot be a static member nor we can have a virtual constructor.

    Let us understand through an example, we will first see a program without the use of virtual keywords and next with the use of virtual.


    C++ Program Overriding a non-virtual function

    // C++ program for function overriding without virtual function
    
    #include <iostream>
    using namespace std;
    
    class Animal
    {
       public:
       void display()
       {
          cout << "I am Animal" << endl;
       }
    };
    
    class Dog: public Animal
    {
       public:
       void display()
       {
          cout << "I am a Dog" << endl;
       }
    };
    
    int main(void)
    {
       Animal *a;
       Dog d;
       
       a = &d;
       a->display();
    
       return 0;
    }

    Output:

    I am Animal

    As you can see in the above program that we created a pointer object for the base class and the function is the same in both of the classes which are to be overridden. But even though the object of the base class points to the derived class (a = &d;), when we call it through an object a, we still get the display() function of the base class.

    Therefore, here we need a virtual function in order to get access to the member of the derived class which we will see in the program below.


    C++ Program Overriding using a virtual function

    // C++ program for function overriding with virtual function
    
    #include <iostream>
    using namespace std;
    
    class Animal
    {
       public:
       virtual void display() //virtual function
       {
          cout << "I am Animal" << endl;
       }
    };
    
    class Dog: public Animal
    {
       public:
       void display()
       {
          cout << "I am a Dog" << endl;
       }
    };
    
    int main(void)
    {
       Animal *a;
       Dog d;
       
       a = &d;
       a->display();
    
       return 0;
    }

    Output:

    I am a Dog

    As you can see above is the same first program but with a virtual display() function. And now the result is different, the base object a which is pointed to the derived class gives the display() function of the derived class indicating the virtual function of the base class is overridden by the derived class.


  • C++ Function Overriding

    Function overriding allows us to define a function at a derived class that is already present in a base class. And that base is said to be overridden. Both derived and base class has the member function with the same name, same return type, and same arguments list.

    And the decision made to call the required function is done at the run time. Hence, it is used to achieve the Runtime polymorphism.

    Let us understand through an example of function overriding using C++. It involves inheritance in a program given below.

    Example of Function Overriding in C++

    // C++ program for function overriding
    
    #include <iostream>
    using namespace std;
    
    class Animal
    {
       public:
       void display()
       {
          cout << "I am Animal" << endl;
       }
    };
    
    class Dog: public Animal
    {
       public:
       void display()
       {
          cout << "I am a Dog" << endl;
       }
    };
    
    int main(void)
    {
       Animal anim = Animal();
       anim.display();	//parent class object 
    
       Dog dg = Dog();
       dg.display();	// derived class object
    
       return 0;
    }

    Output:

    I am Animal
    I am a Dog

  • C++ Overloading (Operator and Function)

    C++ allows us to overload methods, constructor and indexed properties. The function or operator define with the same name but with different types of parameters s called overloading. C++ has two types of overloading and they are:

    • Function overloading
    • Operator overloading

    C++ Function overloading

    Function overloading is a feature of object-oriented programming where multiple functions having the same name differs by their parameters, then these functions are said to be overloaded. When we call those functions, we need to make sure to enter the proper number of arguments along with the proper data type.

    Example: Below are the sample of functions with same name but different arguments.

    // same name different arguments
    int func() { }
    int func(int n) { }
    float func(double d) { }
    int func(int n, double d) { }

    Error example: Now see the example below, the functions defined below have the same name, same number type, and the same number of arguments. In such cases, the compiler will through an error.

    // Compiler throws error
    int func(float num1) { }
    double func(float num2){ }

    The advantage of function overloading is that we do not need to write different names for the functions that perform the same task, increasing the readability of the program. Polymorphism is achieved by function overloading.

    Let us go through an example in C++ for function overloading.

    C++ program for function overloading with different types and different number of parameters

    // C++ program for function overloading
    
    #include <iostream>
    using namespace std;
    
    class OverloadProgram
    {
       public:
       int total(int num1, int num2)
       {
          return num1 + num2;
       }
    
       int total(int num1, int num2, float num3)
       {
          return num1 + num2 + num3;
       }
    };
    
    int main()
    {
       OverloadProgram obj;
    
       //calling first display function
       cout << "Result 1: " << obj.total(50, 40) << endl;
    
       //calling second display function
       cout << "Result 2: " << obj.total(7, 15, 5) << endl;
    
       return 0;
    }

    Output:

    Result 1: 90
    Result 2: 27

    C++ Operator Overloading

    Operator overloading means performing different operations with the same operator. We can overload most of the built-in operators that are available in C++. We can also change the user-defined type as well such as objects and structures.

    The keyword ‘operator‘ is used to overload an operator. Compile-time polymorphism is achieved through operator overloading. It has a return type and parameter list.

    Example: Consider an operator ‘+‘, it is used to add the two numbers but it is also used with string to concatenate two strings. So the ‘+‘ operator when placed between number operands, addition operation is done but when placed between string operands, it concatenates them.

    Syntax: syntax for operator overloading in C++.

    class class_name
    {
        ... .. ...
        public
           return_type operator symbol (arguments_list) {
               //code
           } 
    };

    In the above syntax,

    • return_type is the type that is returned by the function
    • symbol refers to the operator that is to be overloaded such as +, <, -, >, etc.

    However there are few operator that cannot be overloaded and they are:

    • sizeof operator
    • Scope operator (::)
    • ternary operator(?:)
    • member pointer selector(*)

    Let us go through an example in C++ for operator overloading.

    C++ Program for operator overloading

    // Overload ++ program
    
    #include <iostream>
    using namespace std;
    
    class TestOperator
    {
       private:
          int number;
    
       public:
    
         // Constructor
         TestOperator(): number(9) {}
    
         // ++ overloaded
         void operator++()
         {
           ++number; // pre increment by 1
         }
    
         void display()
         {
           cout << "The Count: " << number << endl;
         }
    };
    
    int main()
    {
       TestOperator op;
    
       // Calling the void operator++ ()function
       ++op;
    
       //calling display function
       op.display();
       return 0;
    }

    Output:

    The Count: 10

    Another example for operator overloading in C++.

    // C++ program for operator overloading
    #include <iostream>
    using namespace std;
    
    class Message
    {
      string str;
      public_colon
      Message(string i)
      {
        str = i;
      }
    
      void operator+(Message);
      void display();
    };
    
    void Message::operator+(Message a)
    {
      string msg = str + a.str;
      cout << "The result: " << msg;
    
    }
    
    int main()
    {
      Message m1("Hi, Welcome ");
      Message m2("Home");
    
      m1 + m2;
    
      return 0;
    }

    Output:

    //Output:
    The result: Hi, Welcome Home

    The advantage of operator overloading is that we can perform different operations on the same operand.