Back to Study material
OOP

MODULE 4

Overloading, Templates and Inheritance

 


Introduction and Need of Operator Overloading

  • Operators have fixed meaning and functionalities for primitive data types like int, float, double etc.
  • These operators cannot be used for user defined data types like classes.
  • But the functionality of these operators can be extended to user defined data types like classes.
  • Operator ‘+’ is used to add two integers but we can add two objects by extending the meaning of ‘+’ operator.
  • This is called as operator overloading.
  • We can overload operators so that they can perform operation on objects.
  • Operator overloading provides special meaning to built in operators to perform some specific computation when the operator is used on objects of that class.
  • All C++ operators can be overloaded except following :
  • Class member access operator(.*)
  • Conditional operator(?:)
  • Scope resolution operator(::)
  • Size of operator(sizeof)
  •  

    Operator Function

  • Operator is overloaded with the help of operator function.
  • It defines the operations to be performed by overloaded operator.
  • This operator function can be of two types
  • 1. Member operator function

    2. Non Member operator function

  • Non member operator functions are usually friend functions of class. Operator functions are discussed in preceding section.
  •  

    Overloading using Member Operator Function

       Syntax of an operator function

  • Member operator function is a member of the class.
  • It is declared in a class as follows :
  •  return-type operator OP(argument list);

     Where OP -> operator to be overloaded.

  • Number of parameters in an argument list depends on the type of operator.
  • Type of Operator

    No. of Arguments

    Unary

    0

    Binary

    1

  • Thus according to above table, overloading unary operators using member functions takes no argument and binary operator takes one argument.
  • It is defined as follows :
  • return-type class-name :: operator OP(argument list)

    {

    Operations that overloaded operator performs

    }

     

     

    Overloading Unary Operators using Member Operator Function

    Member operator function takes no parameter for unary operator and is implicitly passed through “this” pointer.

    Overloading Unary Minus(–)

            Program

    Write a program in C++ to overload unary minus(-).

    Solution :

    #include<iostream>

    using namespace std ;

    class Example

    {

     int x,y,z;

     public:

     

    Example(int p,int q,int r)

    {

     x=p;

     y=q;

     z=r;

    }

    void display()

    {

     cout<<x<<” ”<<y<<” ”<<z;

    }

    void operator-()

    {

     x=-x;

     y=-y;

     z=-z;

    }

    };

    int main()

    {

    Example obj (10,-20,30);

    cout<<”Original numbers are”

    obj.display();

    - obj;                                  

    obj.display();

    return 0;

    } 

     

     

    //Defines class Example

     

     

     

     

    //Parameterized constructor

     

     

     

     

     

     

     

     

     

     // Step 1 Operator function to overload minus

     

     

     

     

     

     

     

     

     

     

     

    // Step 2 Invokes operator function

     

     

    cout<<”Numbers after applying unary minus”

    Explanation

  • This program overloads unary – on data members of class Example.
  • It defines operator function to overload unary – so that it can be applied to object. See step 1.
  • void operator-()

    {

     x=-x;

     y=-y;

     z=-z;

    }

    //Operator function to overload minus

     

     

  • This operator function is invoked by applying unary – on object ‘obj’. See step 2.
  • - obj;

    cout<<”Numbers after applying unary minus”

    //Invokes operator function

    Output

    Original numbers are

    10 -20 30

    Numbers after applying unary minus

    -10 20 -30

     

    Overloading ++ and – –

  • ++ and – –are unary operators so member operator function will take no arguments.
  • ++(increment operator) and – – (decrement operator)takes two forms via postfix and prefix. So member operator function for each version must be written separately.
  • It is discussed below.
  •  

    Overloading Prefix versions

    Prefix increment

    Return-type operator ++()

    {

    //Body of operator function

    }

    Example

    void operator++()

    {

    ---

    }

    Prefix decrement

    Return-type operator --()

    {

    //Body of operator function

    }

    Example

    void operator--()

    {

    ---

    }

     

    Postfix versions

    Post Increment

    Return-type operator ++(int x)

    {

    //Body of operator function

    }

     where x is zero.

    Example

    void operator ++(int x)

    {

    ---

    }

    Post Decrement

    Return-type operator --(int x)

    {

    //Body of operator function

    }

    Example

    void operator--(int x)

    {

    ---

    }

     

    Program

    Write a C++ program to overload ++,-- (postfix and prefix versions), !
    (logical not) operator.

    #include<iostream>

    using namespace std ;

    class Example

    int a,b;

    public:

    void accept()

    {

    cout<<”enter values of and b”;

    cin>>a>>b;

    }

    void display()

    {

    cout<<a<<” ”<<b<<” ”;

    }

    void operator++();

    void operator--();

    void operator++(int x);

    void operator--(int x);

    void operator!();

    };

    void Example:: operator++()

    {

    a=++a;

    b=++b;

    }

    void Example:: operator--()

    {

    a=--a;

    b=--b;

    }

    void Example:: operator++(int x)

    {

    a=a++;

    b=b++;

    }

    void Example:: operator--(int x)

    {

    a=a--;

    b=b--;

    }

    void Example:: operator!()

    {

    a=!a;

    b=!b;

    }

    int main()

    {

    Example O;

    obj.accept();

    ++ O;

    obj.display();

    obj ++;

     obj.display();

    -- obj;

    obj.display();

    obj --;

    obj.display();

    ! obj;

    obj.display();

    return 0;

    }

     

     

     

     

     

     

     

     

     

     

     

     

     

     

    //overloads prefix ++

    //overloads prefix --

    //overloads postfix ++

    //overloads postfix --

    //overloads logical not

     

    //Defines operator function to overload prefix version of ++

     

     

     

    //Defines operator function to overload prefix version of --

     

     

     

    //Defines operator function to overload postfix version of ++

     

     

    //Defines operator function to overload postfix version of --

     

     

     

    //Defines operator function to overload logical not

     

     

     

     

     

     

       //Invokes operator

         Functions to perform

         ++ --(postfix and   prefix)and ‘!’

         on object                

    ‘obj’.

     

    Overloading Binary Operators using Member Operator Function

  • Member operator function takes only one parameter for binary operator as left hand side operand is implicitly passed through this pointer.
  • Left hand side object is responsible to invoke operator function.
  •  

  • Overloading plus(+) and minus(–)
  • We can perform addition and subtraction on two objects by overloading + and -.
  • Program

    Write a C++ program to overload binary +, - .

    #include<iostream>

    using namespace std ;

    class Example

    {

    int a,b;

    public:

    Example(int p, int q)

    {

    a=p;

    b=q;

    }

    void display()

    {

    cout<<a<<” ”<<b<<endl;

    }

    Example operator+(Example X);

    Example operator-(Example X);

    };

    Example Example::operator+(Example X)

    {

    Example E;

    E.a= a+X.a;

    E.b= b+X.b;

    return E

    }

    Example Example:: operator-(Example X)

    {

    Example F;

    F.a= a-X.a;

    F.b= b-X.b;

    return F

    }

    int main()

    {

    Example obj1(10,20);

    Example obj2(5,5);

    Example obj3(0,0);

    cout<<”Addition is”

    obj3= obj1+ obj2;

    obj3.display();

    cout<<”Subtraction is”

    obj3= obj1- obj2;

    obj3.display();

    return 0 ;

    }

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     // Step 1 overloads +

    // Step 1 overloads -

     

    // Step 2 Defines operator function to overload +

     

     

     

     

     

    //Defines operator function to overload -

     

     

     

     

     

     

     

     

     

     

     

     

    // Step 3

    //Invokes overloaded binary +

     

    // Step4

    //Invokes overloaded binary -

     

    Explanation

  • This program overloads binary + and -. For this operator functions are declared in class. See step 1.
  • This operator function returns objects which stores addition of two objects.
  • Return type of an object is always a class so it is declared as follows

    Example operator+(Example X);

    Example operator-(Example X);

    //overloads +

    //overloads -

     

  • Operator functions are defined outside class using scope resolution operator. See step 2.
  • Example Example:: operator+(Example X)

    {

    Example E;

    E.a= a+X.a;

    E.b= b+X.b;

    return E;

    }

    Example Example:: operator-(Example X)

    {

    Example F;

    F.a= a-X.a;

    F.b= b-X.b;

    return F;

     

    }

    //Defines operator function to overload +

     

     

     

     

    //Defines operator function to overload -

     

     

     

     

  • Operator function takes only one argument as left hand side operand is passed implicitly via this pointer.
  • This operator function returns object where addition is stored.
  • Return type of an object is always a class so it is declared as follows :
  • Operator function for addition is activated when two objects are added using +. See
    step 3.
  • O3= O1+ O2;

     

    //Invokes overloaded binary +

     

  • Operator function for subtraction is activated when two objects are subtracted using -. See step 4.
  • O3= O1- O2;

    //Invokes overloaded binary -

    Thus the output will be :

    Output

    cout<<”Addition is”

    a 15    b  25

    cout<<”Subtraction is”

    a 5      b  15

     

            Program

    Write C++ program to demonstrate use of binary (“+”) operator overloading to add two complex numbers using member function.             

    #include<iostream>

    using namespace std ;

    class Demo

    {

    int real,imag;

    public:

    Demo(int p, int q)

    {

    real=p;

    imag=q;

    }

    void display()

    {

    cout<<real<<” +j”<<imag<<endl;

    }

    Demo operator+(Demo X);

    };

    Demo Demo::operator+(Demo X)

    {

    Demo D;

    D.real=real+X.real;

    D.imag=imag+D.imag;

    return D

    }

    int main()

    {

    Demo obj1(10,20);

    Demo obj2(5,5);

    Demo obj3(0,0);

    cout<<”Addition is”

    obj3= obj1+ obj2;

    obj3.display();

    return 0 ;

    }

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     //……1overloads +

     

     

    //.2 Defines operator function to overload +

     

     

     

     

     

    //Defines operator function to overload -

     

     

     

     

    //…..3

    //Invokes overloaded binary +

     

     

     

    Operator Overloading using Friend Function

  • Unary Operators
  • Operator function to overload unary operator using friend function takes one argument.
  • Example

     friend void operator-(Example &O);

            Program

    Write a program to overload unary –, ++,--(prefix versions) using friend function.

    #include<iostream>

    using namespace std ;

    class Example

    {

    int x,y,z;

    public:

    Example(int p,int q,int r)

    {

    x=p;

    y=q;

    z=r;

    }

    void display()

    {

    cout<<x<<” ”<<y<<” ”<<z;

    }

    friend void operator-(Example &O);

    friend void operator++(Example &O);

    friend void operator--(Example &O);

    };

    void operator-(Example & O)

    {

    O.x=-O.x;

    O.y=-O.y;

    O.z=-O.z;

     

    }

    void operator++(Example & O)

    {

    O.x=O.x++;

    O.y=O.y++;

    O.z=O.z++;

    }

     

    void operator--(Example & O)

    {

    O.x=O.x--;

    O.y=O.y--;

    O.z=O.z--;

    }

    };

    int main()

    {

    Example O(10,-20,30);

    cout<<”Original numbers are”;

    O.display();

    - O;

    cout<<”Numbers after applying unary minus”;

    O.display();

    ++ O;

    cout<<”Numbers after applying ++”;

    O.display();

    -- O;

    cout<<”Numbers after applying --”;

    O.display();

    return 0 ;

    }

     

     

    //Defines class Example

     

     

     

     

     

    //Parameterized constructor

     

     

     

     

     

     

     

    //Operator functions to overload
    “-”, “++”, “--”

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

    //Invokes operator function for –

     

     

     

    //Invokes operator function for ++

     

     

    //Invokes operator function for --

    Explanation

  • Friend Function does not have this pointer. Thus if we attempt to modify value of an object as an argument to a friend function, changes are made to copy of that object and not on original object.
  • To reflect changes directly to original object, we are using reference parameter in operator friend function.
  • If we overload postfix versions of ++ and – – then operator function will be written as friend Example operator ++(Example &O, int x)
  • 2.      Binary Operators

  • Operator function to overload binary operator using friend function takes two arguments.
  • E.g. friend void operator-(Example O1, Example O2);
  • #include<iostream>

    using namespace std ;

    class Point

    {

    int x,y;

    public:

    Point()

    {}

    Point(int p, int q)

    {

    x=p;

    y=q;

    }

     

    void display()

    {

    cout<<x<<” ”<<y<<endl;

    }

    friend Point operator+(Point P1,Point P2);

    friend Point operator-(Point P1,Point P2);

    };

    Point operator+(Point P1,Point P2)

    {

    Point E;

    E.x= P1.x+P2.x;

    E.y= P1.y+P2.y;

    return E;

    }

    Point operator-(Point P1,Point P2)

    {

    Point E;

    E.x= P1.x-P2.x;

    E.y= P1.y-P2.y;

    return E;

    }

    int main()

    {

    Example obj1(10,20);

    Example obj2(5,5);

    Example obj3(0,0);

    obj3= obj1+ obj2;

    obj3.display();

    obj3= obj1- obj2;

    obj3.display();

    return 0;

    }

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

    //Step 1 overloads + using friend

     

    // Step 2 overloads – using friend

    //Defines operator function to overload +

     

     

     

     

     

     

    //Defines operator function to overload -

     

     

     

     

     

     

     

     

     

     

     

    //Invokes overloaded binary +

     

    //Invokes overloaded binary -

    Explanation

  • Here we are overloading binary operators using friend, hence it takes two arguments. Here arguments are objects as usually friend functions take object as arguments. See steps 1 and 2.
  • friend Point operator+(Point P1,Point P2);

    friend Point operator-(Point P1,Point P2);

    //overloads + using friend

    //overloads – using friend

     

  • Operator function returns object E. Return type of object is always a class. Hence return type of operation function will be class “Point” to which object “E” belongs. 
  • Hence friend function is declared as follows :
  • Following operators cannot be overloaded using friends :
  • 1. () Function call operator

    2. =  Assignment operator

    3. [] subscripting operator

    4. -> class member access operator

  • The chart given below summarizes no of arguments in operator function :
  •    Type of      operator

    Type

    of operator

    function

    Unary

    Binary

    Member Function

    0

    1

    Friend Function

    1

    2

            Program

    Write a C++ program to add the complex numbers using friend function.

     

     

    #include<iostream>

    using namespace std ;

    class Example

    {

    int real, imag;

    public:

    Example(int p, int q)

    {

    real=p;

    imag=q;

    }

    void display()

    {

    cout<<real<<”<<imag<<endl;

    }

    friend Example operator+(Example X1,Example X2);

    };

     Example operator+(Example  X1, Example X2)

    {

    Example E;

    E.real= X1.real+X2.real;

    E.imag= X1.imag+X2.imag;

    return E;

    }

    int main()

    {

    Example obj1(10,20);

    Example obj2(5,5);

    Example obj3(0,0);

    cout<<Addition is”

    obj3= obj1+ obj2;

    obj 3.display();

    return 0;

    }

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

    //Defines operator function to overload+

     

     

     

     

     

     

     

     

     

     

     

     

    //Invokes overloaded binary+

     

     

            Program

    Write a C++ program to subtract 2 complex numbers using concept of overloading using friends function.

     

    Solution :

    #include<iostream>

    using namespace std ;

    class Example

    {

    int real, imag;

    public:

    Example(int p, int q)

    {

    real=p;

    imag=q;

    }

    void display()

    {

    cout<<real<<”+j”<<imag<<endl;

    }

    friend Example operator-(Example X1,Example X2);

    };

     Example operator-(Example X1, Example X2)

    {

    Example E;

    E.real= X1.real-X2.real;

    E.imag= X1.imag-X2.imag;

    return E;

    }

    int main()

    {

    Example obj1(10,20);

    Example obj2(5,5);

    Example obj3(0,0);

    cout<<Subtraction is”

    obj3= obj1- obj2;

    obj3.display();

    return 0;

    }

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

    //Defines operator function to overload -

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

    //Invokes overloaded binary -

     

     

     

    Overloading Relational and Logical Operators

  • There are six relational operators in C++
  • Equality(==)

    Less than(<)

    Less than equal to(<=)

    Greater than(>)

    Greater than equal to(>=)

    Inequality(!=)

  • There are three logical operators
  • Logical AND (&&)

    Logical OR (||)

    Logical NOT (!)

  • We can overload relational operators <,>,<=,>=, == which can be used to compare the objects of class.
  • We will overload only equality and less than operator. Others can be implemented using these two operators by following techniques.
  • a!=b  return !(a==b)

    a>b  return(b<a)

    a<=b  return!(b<a)

    a>=b       return!(a<b)

  • Relational and logical operators can be overloaded using following skeleton
  • bool class_name::operator symbol(const class_name & rhs)

    {

    Compare this and rhs and return true and false accordingly

    }

    Where rhs= right hand side operand

  • Overloading of’ =’ , ‘&& ’ and ’ <’ operators is shown below.
  • #include<iostream>

    using namespace std;

    class overload

    {

    private:

    int a,b;

    public:

    overload (int x, int y)    //constructor to initialize variables

    {

    a=x;

    b=y;

    }

    bool operator <(const overload &o1)   // overloading < operator

    {

    If( (a<o1.a)&&(b<o1.b))

    {

    return true;

    else

    return false;

    }

    bool operator ==(const overload &o1)   // overloading == operator

    {

    return ((a==o1.a)&&(b==o1.b));

    }

    };

    int main()

    {

    overload object1(10,20); 

    overload object2(11,21);

    if(object1<object2)   // Compare two objects

    cout<<”Values of object 1 are less than values of Object2”;

    else

    cout<<”Values of object 1 are not less than values of Object2”;

    if(object1==object2)

    cout<<”Values of object 1 are equal to values of Object2”;

    else

    cout<<”Values of object 1 are not equal to values of Object2”;

    return 0;

    }

     

     

    Overloading new delete and Assignment Operator

  • Overloading New and Delete
  • new and delete operators can be overloaded using following code.

    void *operator new(size_t size)

    {

    return malloc(size);    //Perform allocation

    }

    Where size is number of bytes of memory of data type size_t.

    Return type of overloaded new must be void* as it must return pointer to memory that it allocates or throw bad_alloc exception if an allocation error occurs.

    void *operator delete(void *P)

    {

    free(*P);   // free memory pointed by P

    }

    Where *P is a pointer to memory to be freed.

            Program

    Program to overload new and delete operator.

    #include<iostream>

    using namespace std;

    class Employee

    {

    int id;

    int salary;

    public:

    Employee(int x, int y)

    {

    id=x;

    salary=y;

    }

    void display()

    {

    cout<<”Employee id:”<<id<<endl;

    cout<<”Employee salary:”<<salary<<endl;

    }

    void *operator new(size_t size );

    void operator delete(void *p);

    };

    void *Employee::operator new(size_t size )

    {

    void *p;

    cout<<”Overloading new”<<endl;

    p=malloc(size);

    if(!p)

    {

    bad_alloc b;

    throw b;

    }

     

    return p;

    }

    void Employee:: operator delete(void *p)

    {

    cout<<”Overloading delete”<<endl;

    free(p);

    }

    int main()

    {

    Employee *E1,*E2;

    try

    {

    E1= new Employee(10,50000);

    }catch(bad_alloc ba)

    {

    cout<<”Allocation error for E1”;

    return 1;

    }

    try

    {

    E2= new Employee(11,60000);

    }catch(bad_alloc ba)

    {

    cout<<”Allocation error for E2”;

    return 1;

    }

    E1->display();

    E2->display();

    delete E1;

    delete E2;

    return 0;

    }

    Output

    Overloading new

    Overloading new

    10 50000

    11 60000

    Overloading delete

    Overloading delete

    2.       Overloading Assignment Operator

    We can assign one object to another by overloading assignment operator.

            Program

    Write a C++ program to overload assignment operator(=) . 

    #include<iostream>

    using namespace std ;

    class Example

    {

    int a,b;

    public:

    Example(int p, int q)

    {

    a=p;

    b=q;

    }

     

    void display()

    {

    cout<<a<<” ”<<b<<endl;

    }

    Example operator=(Example X); 

    };

    Example Example:: operator=(Example X)

    {

    a= X.a;

    b= X.b;

    return this*;

    }

    int main()

    {

    Example obj1(10,20);

    Example obj2(0,0);

    cout<<”Before  Assignment”;

     

    obj2.display();

    obj2= obj1;

    cout<<”After Assignment”;

    obj2.display();

    return 0;

    }

     

     

     

     

     

     

    //parameterized constructor

     

     

     

     

     

     

     

     

     

    // Step 1 overloads =

     

    // Step 2 Defines operator function to overload =

     

     

     

     

     

     

     

     

     

     

     

    // Step 3 Invokes overloaded assignment operator

    Explanation

  • Operator function for assignment operator is declared in a class. See step 1.
  • This operator function returns object on which assignment operator is applied.
  • Return type of an object is always a class so it is declared  as follows :
  • Operator function is defined as follows .See step 2
  • Example Example:: operator=(Example X)

    {

    a= X.a;

    b= X.b;

    return this*;

    }

  • Here assignment operation is performed on data members of object. This object is returned through this * pointer. It points to an object that generated call to operator function.
  • Operator function is invoked by statement obj2= obj1 . See step 3.
  • The object returned by this pointer in step 2 is then assigned to object obj2.
  • It is then displayed using statement
  • obj2.display();
  • C++ provides overloaded assignment operation by default, even if it is not explicitly overloaded.
  •  

    Output 

    Before  Assignment

    a 0 b 0

    After  Assignment

    a 10 b 20

     

    Rules of Operator Overloading

       Operators which cannot be overloaded

    All C++ operators can be overloaded except following

  • Class member access operator(.*)
  • Conditional operator(?:)
  • Scope resolution operator(::)
  • Size of operator(sizeof)
  •    Operators which cannot be overloaded by using Friend Function

    Following operators cannot be overloaded using friends

  • () Function call operator
  • =  Assignment operator
  • [] subscripting operator
  • -> class member access operator
  •    Rules for operator overloading 

  • Some operators like (assignment)=, (address)& and comma (,) are by default overloaded.
  • We cannot create new operators for overloading. Only built in operators can be overloaded.
  • We cannot redefine meaning of in built operators i.e we cannot change the meaning +, - etc.
  • Precedence and associativity of operators cannot be changed.
  • Overloaded operators cannot have default arguments.
  • Operators overloaded using member functions takes no argument for unary and one argument for binary operator.
  • Operators overloaded using friend functions takes one argument for unary and two arguments for binary operator.
  •  


  • Function overloading is one of the way to achieve compile time polymorphism in c++.
  • Overloaded functions have same function name and different argument list.
  • F1 void accept(int x);

    F2 void accept(float y);

    F3 void accept(int x, int y);

    Here accept function is overloaded.

  • F1 and F2 are overloaded as they have same function name but different argument list.
  • Though argument list consists of single argument it is of different data type.
  • F1 and F3 are overloaded as they have same function name and number of arguments are different.
  • F2 and F3 are overloaded as they have same function name and number of arguments are different.
  • Argument list may have different number of arguments OR different data type of arguments OR both.
  • Return type of functions may be same or different.
  •    int add(int x, int y);

       float add(int x, int y);

     Here add functions have different return types but they have same argument list. So they are not overloaded functions.

     Thus return type does not play any role in function overloading.

  • Overloaded functions perform tasks of similar nature.
  • As all overloaded functions have same name compiler determines the function to be called on the basis of argument list.
  • Compiler searches for the exact match of function prototype and then executes corresponding function.
  • Table : Function prototypes and required function calls

    Sr. No.

    Function Protoypes

    Function calls

    1.

    void accept(int x);

    accept(10);

    2.

    void accept(float y);

    accept(1.5);

    3.

    void accept(int x, int y);

    accept(10,20);

            Program

    Write a C++ program to calculate the area of circle, rectangle and triangle using function overloading.                

    Solution :

    #include<iostream>

    using namespace std ;

    #include<conio.h>

    #define pi 3.14

    class Sample       //Defines class Sample

    {         

     public:

     void area(int x)      // 1.Calculates area of circle

    {

    int y= pi*x*x;       

    cout<<“Area of circle is ”<<y;

    }

    void area(int a, int b)      // 2.Calculates area of rectangle

    {         

    int c= a*b;       

    cout<<“Area of rectangle is”<<c;

    }

    void area(float p,float q)    // 3.Calculates area of triangle

    {

    int s= 0.5*p*q;      

    cout<<“area of triangle is”<<s;

    }

    };         

    int main()       

    {    

    Sample obj ;     

    obj.area(10);                                  // Step 4 Function call for area for circle

    obj.area(10,20);                               // Function call for area for rectangle

    obj.area(1.5,2.5);                           // Function call for area for triangle

    return0 ;

    }

    Explanation

    This program calculates area for circle, rectangle and triangle. For this we are overloading “area” function.

    Step 1 : Here x denotes radius of circle. This version of “area” calculates area of circle and hence radius is passed as parameter.

    void area(int x)

    {

    int y= pi*x*x;

    cout<<“Area of circle is”<<y;

    }  

     

     

    //Calculates area of circle

     

    Step 2 : Here a and b denote length and breadth of rectangle. This version of “area” calculates area of rectangle and hence length and breadth are passed as parameters.

    void area(int a,int b)

    {

    int c= a*b;

    cout<<“Area of rectangle is”<<c;

    } 

     

     

    //Calculates area of Rectangle

    Step 3 : Here p and q denote base and height of triangle. This version of “area” calculates area of triangle and hence base and height are passed as parameters.

    void area(float p,float q)

    {

    int s= 0.5*p*q;

    cout<<“area of triangle is”<<s;

    }

     

     

    //Calculates area of triangle

    Step 4 : It denotes function calls for different versions of area depending upon type of geometrical figure.

    int main()

    {

    Sample obj;

    obj.area(10);

    obj.area(10,20);

    obj.area(1.5,2.5);

    return0;

    }

     

     

    //Function call for area for circle

    //Function call for area for rectangle

    //Function call for area for triangle

     


  • The general form of template function is as follows :
  • template <class Ttype> return-type function-name(parameter list)

    {

    //body of function

    }

    Or

    template <class Ttype>

    return-type function-name(parameter list)

    {

    //body of function

    }

    Where Ttype -> data type used by the function.

  • Once we create a template function, we can use it for any data type.
  • Compiler will automatically generate correct version of template function depending upon data type passed in it.
  • Thus template function is function that overloads itself.
  • This data type is passed as parameter in template function. Hence templates are also called as parameterized functions.
  • Function Templates are also called as generic functions.
  • Program

    Write a C++ program for a function template that returns the maximum of two values.                           

    Solution :

    #include<iostream.h>

    template <class T>

    void max1(T x,T y)

    {

    if(x>y)

    cout<<x<< “is greater”;

    else

    cout<<y<<”is greater”; 

    }

    int main()

    {

    cout<<"\nInteger"<<max1(3,7);         cout<<"\nFloat"<<max1(44.66,22.13);

    cout<<"\nCharacter  "<<max1('t','p');

     return 0;

    }

     

     

    // Step 1

     

    //Here, condition is checked

     

     

     

     

     

     

    //Step 2 Integers are passed.

    //Step 3 float are passed.

    // Step 4 Characters are passed.

    Explanation

    Step 1 :  Function template for finding maximum of two numbers is written where T represents generic data type. T will be replaced by specific data type depending upon type of parameter passed to function ‘max1’.

    void max1 (Tx, Ty)

    Step 2 :  When we pass integer value to the function, ‘T’ will act as integer type. Thus it finds maximum of two integers.

    cout<<"\nInteger"<<max1(3,7);

    Step 3 :  When we pass float value to the function, ‘T’ will act as float type. Thus it finds maximum of two floats.

    cout<<"\nFloat "<<max1(44.66,22.13);

    Step 4 :  When we passed character value to the function, ‘T’ will act as character type. Thus it finds maximum of two characters.

    cout<<"\nCharacter  "<<max1('t','p');

    Thus Single function is working for all three datatypes.

    Output

    Integer : 7

    Float : 44.66

    Character : t

    Program

    Write a C++ program to swap two numbers using concept of function template.

    Solution :

    #include<iostream>

    using namespace std;

    template <class T>

    void swapnums(T &x,T &y)

    {

    T temp;

    temp=x

    x=y;

    y=temp;

    }

    int main()

    {

    swapnums (10, 11);

    swapnums (10.5, 11.5);

    swapnums (‘A’, ‘D’);

    return 0;

    }

     

     

     

    //Function template for swapping

     

     

     

     

     

     

     

     

    Program

    Write a program in C++ for bubble sort using function template.

    Solution :

    #include<iostream>

    using namespace std;

    template <class T>

    void bubblesort(T A[], int  n)

    {

    for(int i=0;i<=n-1;i++)

          for(int j=n-1;i<j;j--)

          if(A[j]<A[j-1])

         {

    swap (A[j], A[j-1])

    }

     template <class X>

    void swap(X &p, X &q)

    {

    X temp=p;

    p=q;

    q=temp;

    }

     

    int main()

    {

    int array[5];

    cout<<“Enter elements of array”;

    for(int i=0;i<5;i++)

    {

    cin>>a[i];

    }

    bubblesort(array,5);

    cout<<“Sorted array”;

    for(int i=0;i<5;i++)

    {

    cout<<array[i]<<“”;

    return 0;

    }

     

     

     

     //template function for bubble sort

     

     

     

     

     

     // calls template function for swap

     

    // template function for swap

     

     

     

     

     

     

     

     

     

     

     

     //accept array elements for sorting

     

     

     

     

     //calls template function for sorting

    Output

    Enter elements of array

    25 15 30 10 50

    Sorted array 10 15 25 30 50

    Program

    Write a program to display integer value, float value, character and string by using single function.

    Solution :

    #include<iostream>

    using namespace std;

    #include<conio.h>

    template <class T>

    void display(T x)

    {

     cout<<x<<"\n";

    }

    int main()

    {

     display(20);

     display(44.3);

     display('A');

     display("welcome");

    return0;

    }

    Output

    20

    44.3

    A

    welcome

    Template Arguments in Member Function Template

  • Member function template can have more than one generic data type as arguments.
  • All these generic data types are separated by comma.
  • It is written as shown :
  •  template<class T1, class T2,.... class Tn>

     return-type function-name(T1 arg, T2 arg,...Tn arg)

     {

     Function Body

     }

    Example :

     template<class T1, class T2>

     void Demo(T1 a, T2 b)

     {

     cout<<a< “ ”<<b;

     }

  • Here function Demo takes two arguments of two different generic data types viz. T1 and T2.
  • Program

    Program to illustrate multiple template arguments in member function.

    Solution :

     #include<iostream>

    using namespace std;

     #include<conio.h>

     template<class T1, class T2>// Step 1

     void Demo(T1 a, T2 b)

     {

     cout<<a<<” ”<<b;

     }

     void main()

     {

     Demo(10,20.5); // Step 2

     Demo(20.9, ‘A’);// Step 3

     Demo(‘X’, “Object Oriented”);// Step 4

     }

    Explanation

    Step 1 :  This program designs template function with two arguments of generic type T1 and T2.

    Step 2 :  The statement

     Demo(10,20.5)

     invokes template function. T1 will be replaced by 10(int) and T2 will be replaced by 20.5(float).

    Step 3 :  The statement

     Demo(20.9, ‘A’)

     invokes template function. T1 will be replaced by 20.9 (float) and T2 will be replaced by A(char).

    Step 4 :

    Demo(‘X’, “Object Oriented”)

     invokes template function. T1 will be replaced by X(char) and T2 will be replaced by Object Oriented (string).

    Overloading Template Function

  • Although template function overloads itself, we can explicitly overload template function. In this case overloaded function overrides template function relative to that specific version.
  • #include<iostream>

     

     

    //Template function

    template <class T>

     

    void display(T x)

     

    {

     

    cout<<"\n Inside template function : x : "<<x;

    //Take any type of data (like int, float, string etc.)

    }

     

    //Normal function

     

    void display(int x)

     

    {

     

    cout<<"\n Inside normal function : x : "<<x;

    //Take only integer type.

    }

    //This function overrides template                                                                                function

    void main ()

     

    {

     

    display(21.45);

    //calls template function

    display(45);

    //calls normal function

    display("Object oriented");

    // calls template function

    }

     

    Output

    Inside template function : x :21.45

    Inside normal function : x : 45

    Inside template function : x : Object Oriented

  • There are two functions with same name and same parameter. In above example we are overloading generic function with normal function. When we are calling function with integer argument, normal function is called.
  • Function Overloading Vs Function Template

    Function overloading

    Function Template

    Data types used in overloaded function are primitive data types

    Eg. void add(int a, int b);

           void add(float a, int b);

     

                     Primitive  data type

    Data types used in template function are generic data types

    template<class T1, class T2>

    void Demo(T1 a, T2 b)

                        Generic type

    All the versions of overloaded functions must be explicitly specified.

    Eg. P1. void add(int a, int b);

    P2. void add(float a, int b);

    P3. void add(int a, int b, int c);

    Function call add(10,20) will invoke P1

    While add(10.5, 5) will invoke P2

    Function template takes various versions depending on the type of argument passed to it.

    template<class T1, class T2>

    void Demo(T1 a, T2 b)

    Demo function will take version Demo(int, int) for function call Demo(10,20). Similarly for function call Demo(10.5,5) version will be Demo(float, int) . Thus function template automatically overloads itself.

    It does not support generic programming.

    It supports generic programming.

    Every overloaded function will have separate definition.

    Function template have same definition for all versions of it.

    Example:

    void Data(int a, int b, int c);

    void Data(float a, float b, float c);

    void Data(int a, float b);

     

    Example:

    template<class T1, class T2>

    void Demo(T1 a, T2 b)

    {

    }

     


  • Class template defines a generic class that specifies all the functions used by the class. However, the type of data on which function works will be specified as a parameter, when objects of that class are created.
  • Thus they are also called as parameterized classes.
  • Assume we have created a stack class that stores integer values. Now if we want to store float values in stack, we have to recreate stack class to store float values.
  • This can be avoided by creating template class. Its general form is as follows :
  • Syntax

    template<class T>

    class class_name

    {

     -------------

      class members

      -------------

    };

    Program

    Consider class Demo, where we want to find average of three numbers(numbers can be integer or float).

     

    Solution :

    #include<iostream>

    using namespace std;

    template <class T>

    class Demo           //Step 1

    {

     private:

      T n1,n2,n3;

     public:

                           Demo(T x, T y, T z)

    {

       n1=x;

       n2=y;

       n3=z;

                           }

      void avg()            //Step 2 

      {

     

     cout<<" "<<(n1+n2+n3)/3;

    }

     

    };

    int main()

    { 

    Demo<int>s1(10,20,30);           //Step 3

    Demo<float>s2(50.5,40.5,30.5);    //Step 4

    cout<<"\n Average = ";         //Step 5

    s1.avg();

    cout<<"\n Average = ";

    s2.avg();

    return 0;

    }

    Explanation

    Steps

    Step 1 : ‘Demo’ is a template class that defines function ‘avg’.

    Class Demo

    Step 2 : ‘avg’ function calculates average of three numbers.

      void avg()

      {

     

       cout<<" "<<(n1+n2+n3)/3;

      }

    Step 3 : It creates object s1 that stores integer type variables.

    Demo<int>s1(10,20,30);

    Step 4 : It creates object s2 that stores float type variables.

    Demo<float>s2(50.5,40.5,30.5);

    Step 5 : Calculates average of three integer numbers.

    cout<<"\n Average = ";

    s1.avg();

    Step 6 : Calculates average of three float numbers.

    cout<<"\n Average = ";

    s2.avg();

    Output

     Average = 20

    Average = 40.5

     

     


    Single Inheritance

            It consists of single base and single derived class.

            Derived class inherits all the protected and public members from single base class.

            Private data members of base class will not be inherited.

                      General form

    class derived-class : access specifier base-class

    {

    //Body of derived class

    };

     

     

     

     

    Fig: Single Inheritance

     

     

    class A

    {

    //Body of class A

    };

    class B : public A

    {

    //Body of class B

    };



    Program

    Write a program in C++ to illustrate single inheritance.

     

    Solution :

    #include<iostream>

    using namespace std ;

    class Employee

    {

    protected:

    int id;

    char name[10];

    public:

     void accept()

    {

    cout<<“Enter id of employee”;

    cin>>id;

    cout<<“Enter name of employee”;

    cin>>name;

    }

    };

     class Salary: public Employee

    {

    protected:

    float amount, hra, da, basic;

    public:

    void getdata()

    {

    accept();

    cout<<“enter basic, da and hra”;

    cin>>basic>>da>>hra;

    }

    void display()

    {

    amount=basic+da+hra;

    cout<<“NAME:”<<name<<endl;

    cout<<“ID:”<<id<<endl;

    cout<<“SALARY:”<<amount;

    }

    };

    int main()

    {

    Salary S;

    S.getdata();

    S.display();

    return 0 ;

    }

    //Declares header file

     

    //Step 1 Declares and defines base class Employee

     

    //Step 2 Declares id and name under protected section

     

     

     

    //Step 3 Defines accept function under public section

     

    //Accepting id and name of employee

     

     

     

    //End of accept function

    //End of class Employee

    //Step 4 Create derived class Salary from base class Employee

     

    //Step 5 Declares data members under protected section

     

    //Step 6 Defines getdata function

     

    //Step 7 Calls accept function

    //Accepting details of salary

     

    //End of getdata function

    //Step 8 Defines display function

     

    //Calculates salary

     

    //Displaying name id and salary of employee

     

    //End of display function

    //End of derived class salary

    //Starts main function

     

    //Step 9 Creates object S

    //Step 10 Calls getdata function

    //Calls display function

    Explanation

    Step 1 : Creates base class Employee.

     As it is single inheritance only one base class is there.

    class Employee //Declares and defines base class Employee

    Step 2 :  id and name are declared under protected section so that they are accessible to its immediate derived class .

    protected:

    int id;  //Declares id and name under protected section

    char name[10];

    Step 3 :  Accept function accepts details of employee.

    void accept()  //Defines accept function under public section

    {        

    cout<<“Enter id of employee”;

    //Accepting id and name of employee

    cin>>id;

    cout<<“Enter name of employee”;

    cin>>name;

    }   //End of accept function

    Step 4 :  Creates derived class Salary from base class under public derivation.

      All protected members remains protected and public members remain public in public derivation.

    class Salary: public Employee 

    //Create derived class Salary from base class Employee

     So data members in class Salary are as follows :

    Salary

    Protected

    Public

     

    id

    name

    amount

    hra

    da

    basic

     

    accept()

    getdata()

    display()

    Step 5 : Declares basic, hra, da for calculation of salary.

    float amount, hra, da, basic;

    Step 6 :  getdata accepts hra, da and basic to calculate salary.

    void getdata() //Defines getdata function

    Step 7 :  getdata() calls accept() to get id and name.

      Member function can call another member function of same class or base class directly.

      getdata() calls accept() directly as it belongs to base class.

    accept();  //Calls accept function

    cout<<“enter basic, da and hra”;

    cin>>basic>>da>>hra;  //Accepting details of salary

    Step 8 : Calculates salary and displays details of employee

    void display() //Defines display function

    {

    amount=basic+da+hra; //Calculates salary

    cout<<“NAME:”<<name<<endl;

     //Displaying name id and salary of employee

    cout<<“ID:”<<id<<endl;

    cout<<“SALARY:”<<amount;

    }    //End of display function

    Step 9 :  Creates object of derived class Salary.

      In inheritance object of derived class is created because derived class has access to base class but base class does not have any knowledge of its derived classes down the hierarchy.

    Salary S;    //Creates object S

    Step 10 : Calls member functions with the help of objects and dot operator.

    S.getdata();   //Calls getdata function

    S.display();   //Calls display function

    Multiple Inheritance

                      Multiple inheritance with syntax 

            It consists of multiple base classes and single derived class.

            Derived class inherits protected and public members from multiple base classes.

            If there are two base classes, then derived class inherits features from both the classes.

                      General form

    class derived-class : access specifier base-class1, access specifier base-class2

    {

    //Body of derived class

    };

     

    Fig: Multiple Inheritance

     

     

    class A

    {

      //Body of class A

    };

    class B

    {

       //Body of class B

    };

    class C : public A, public B

    {

     //Body of class C

    };

          Program

    Write a C++ program to illustrate multiple inheritance.

     

    \\madhav\TIFF\2015\Subject\Problem Solving Concepts and Object oriented Concept_PU\8.6.2015\Chp_5\5_2_4.tif 

     

    Fig. P. 5.4.2

    Solution :

    Fig. P. 5.4.2shows multiple inheritance where Employee, Person, Manager are classes and name, age, Department, salary, are data members of these classes.

    #include<iostream>

    using namespace std ;

    class Person

    {

    protected:

    char Name[10];

    int age;

    public:

    void accept()

    {

    cout<<“Enter name of person”;

    cin>>Name;

    cout<<“Enter age of person”;

    cin>> age;

    }

    };

    class Employee

    {

    protected:

    char dept[20];

    public:

    void getdata()

    {

    cout<<“Enter department of employee”;

    cin>> dept;

    }

    };

    class Manager : public Person ,public Employee

    {

    protected:

    int salary;

    public:

    void acceptdata()

    {

    cout<<“Enter salary of employee”;

    cin>>salary;

    }

    void display()

    {

    cout<<“Name of Manager is”<<name;

    cout<<“Age of Manager is”<<age;

    cout<<“Department of Manager is”<<dept;

    cout<<“Salary of Manager is”<<salary;

    }

    };

    int main()

    {

    Manager obj;

    obj.accept();

    obj.getdata();

    obj.acceptdata();

    obj.display();

    return 0;

    }

     

     

    //Step 1 Defines base class Person

     

     

     

     

    //Accept details of Person

     

     

     

     

     

     

    //Step 2 Defines another base class Employee

     

     

     

    //Accept details of Employee

     

     

     

     

     

     

    //Step 3 Defines sub class Manager

     

     

     

     

     

    //Accept details of salary

     

     

    //Displays details of Manager

     

     

     

     

    //Defines main function

     

    //Creates object of Manager

    //Access member functions of classes to display details of Manager.

    Explanation

    Step 1 : Defines base class Person with data members name and age and function accept().

      Data members are declared under protected section so that they are accessible to derived class.

    class Person

    {

    protected:

    char Name[10];

    int age;

    public:

    void accept()

    {

    cout<<“Enter name of person”;

    cin>>Name;

    cout<<“Enter age of person”;

    cin>> age;

    }

    };

    //Defines base class Person

     

     

     

     

     

    //Accept details of Person

     

     

     

     

     

     

     

    Step 2 :  Defines another base class Employee.

    class Employee

    {

    protected:

    char dept[20];

    public:

    void getdata()

    {

    cout<<“Enter department of employee”;

    cin>> dept;

    }};

    //Defines another base class Employee

     

     

     

     

    //Accept details of Employee

     

     

     

     

    Step 3 : Defines sub class Manager that is derived from two classes Person and Employee.

            Data member is salary.

            acceptdata() function accepts salary of employee.

            display() function displays all the details of Manager.

            display() function of subclass Manager can access all the data members of super classes as they are declared under protected section and inherited under public derivation.

    class Manager : public Person ,public Employee

    {

    protected:

    int salary;

    public:

    void acceptdata()

    {

    cout<<“Enter salary of employee”;

    cin>>salary;

    }

    void display()

    {

    cout<<“Name of Manager is”<<name;

    cout<<“Age of Manager is”<<age;

    cout<<“Department of Manager is”<<dept;

    cout<<“Salary of Manager is”<<salary;

    }

    };

    //Defines sub class Manager

     

     

    //Accept details of salary

     

     

     

     

    //Displays details of Manager

     

     

     

     

     

    Step 4 : Creates object of derived class .This object can access all the public and protected data members and member functions of super classes.

    Manager obj;

    //Creates object of Manager

    Step 5 : Calls accept() function.

    obj.accept();

    Step 6 : Calls getdata() function.

    obj.getdata();

     

     

    Step 7 : Calls acceptdata() function.

    obj.acceptdata();

    Step 8 : Calls display()function.

    obj.display();

     


  • When two or more classes are derived from a common base class, we can prevent multiple copies of the base class being present in a derived class by declaring the base class as virtual. Such a base class is known as virtual base class.
  • When base class is made virtual, only one copy of base class data members is inherited in derived class.
  • So the structure of classes will be as follows :
  • class Employee

    {

     

    };

    class Project: public virtual Employee

    {

     

    };

    class Salary: virtual public Employee

    {

    };

    class Employee_Info: public Project, public Salary

    {

    };

    Program is as follows :

    class Employee

    {

    protected:

    char Emp_Name[10];

    char dept[20];

    public:

    void accept()

    {

    cout<<”Enter name of employee”;

    cin>>Emp_Name;

    cout<<”Enter department of employee”;

    cin>> dept;

    }

    };

    class Project : public virtual Employee

    {

    protected:

    char Pro_name[10];

    int Pro_id;

    public:

    void getdata()

    {

    cout<<”Enter name of project”;

    cin>>Pro_name;

    cout<<”Enter id of project”;

    cin>>Pro_id;

    }

    };

    class Salary : virtual public Employee             

    {

    protected:

    int amount;

    public:

    void acceptdata()

    {

    cout<<”Enter amount of salary”;

    cin>>amount;

    }

    };

    class Emp_Info : public Project, public Salary

    {

    public:

    void display()

    {

    cout<<”Employee details are”

    cout<<”Name of employee is”<<Emp_Name;

    cout<<”Department of employee is”<<dept;

    cout<<”Name of Project is”<<Pro_name;

    cout<<” Id of Project is”<<Pro_id;

    cout<<”Salary of employee is”<<amount;

    }

    };

    int main()

    {

    Emp_Info obj;

    obj.accept();

    obj.getdata();

    obj.acceptdata();

    obj.display();

    return 0;

    }

    //Defines base class Employee

     

     

     

     

     

    //Accept details of employee

     

     

     

     

     

     

     

    //Defines sub class project that inherits Employee virtually

     

     

     

     

     

     

    //Accept details of Project

     

     

     

     

     

     

     

     

     

    //Accept details of salary

     

     

     

     

     

     

    //Defines sub class Emp_Info

     

     

     

     

     

     

    //Displays details of employee

     

     

     

     

    //Defines main function

     

    //Creates object of Emp_Info

    //Access member functions of classes to display details of employee.

    Output 

    Enter name of employee

    John Mathew

    Enter department of employee

    Information Technology

    Enter name of project

    Employee Database

    Enter id of project

    11

    Enter amount of salary

    50000

    Employee details are

    Name of employee is: John Mathew

    Department of employee is: Information Technology

    Name of Project is: Employee Database

    Id of Project is : 11

    Salary of employee is: 50000

    Virtual and public keywords can be used in either order.

     

     


    Abstract class is a base class , all the concrete classes can inherit abstract class.

    Characteristic of Abstract class.

  • Instance of a class cannot be created.
  • Abstract class can have pointers and references of abstract class.
  • With pure virtual Variables and normal functions can be defined in abstract class.
  • Abstract class is a parent class and derived classes of abstract class can use its interface.
  •  


  • Pointer is used to access the private member variables stored in memory locations. Pointer is public memory variable. Private and Public  member variables are stored in memory. Pointer holds memory location of variable.
  • is used declare the pointer with an identifier.
  • Example

  • Working of inheritance is same as pointer. The base class and derived class member variables are stored in memory locations.
  • Inheritance, in which from existing class new class is generated with properties of existing class.
  • Inheritance provides code reusability.
  • Public, Private and protected Access specifier can be used.
  • Syntax
  •  

    Example 

    Output is – Child id is 10.

                         Parent id is 80.

     

     


    Index
    Notes
    Highlighted
    Underlined
    :
    Browse by Topics
    :
    Notes
    Highlighted
    Underlined