Sunday, 11 March 2018

Function Overriding In C++

Same function name and same parameter is called function overriding
It may contain same function name and same parameters with same data types,return type and order(number of arguments)
It occurs in different class.
It can only be done in derived class.
It provides slow execution than overloading.
It  require inheritance.
virtual keyword is used before base class function name if you want to make  same function to override in derived class.
Example:
runtime polymorphism

Example:
 ClassA
{
public:
      virtual void display(int a)
{
 cout << "value of a :"<<a;
}
};

Class B:public A
{
public:
       void display(int a)
{
cout << "value of a :"<<a*a;
}
};

Example : same method name and same parameters with same data types,return type and order(number of arguments)

#include<iostream.h>
#include<conio.h>
class A
{
public:
  virtual void display(int a)
{
 cout << "value of a :"<<a<<endl;
}
};

class B:public A
{
public:
       void display(int a)
{
cout << "square value of a :"<<a*a;
}
};

void main()
{
    clrscr();
     A a1;
    a1.display(5);
    B b1;
    b1.display(5);
   getch();
}
Output:
value of a:5
square value of a:25



No comments:

Post a Comment

apply function in R

1) apply function: It takes 3 arguments matrix,margin and function.. Example: m<-matrix(c(1,2,3,4),nrow=2,ncol=2) m #1 indicates it is ap...