CSE Assignment Virtual Function

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 6

Date:

29 Aug

2016
Q7. Write a C++ program to implement Polymorphism using the
concept of Virtual functions
#include<iostream>
#include<stdlib.h>
using namespace std;
class BaseClass{
public:
virtual void Display(){
cout<<"You are accessing Display Function of Superclass"<<endl;
}
};

class DerivedClass:public BaseClass{


public:
void Display(){
cout<<"You are accessing Display Function of Derived Class"<<endl;
}
};

class DerivedClass2:public DerivedClass{


public:
void Display(){
cout<<"You are accessing Display Function of Derived Class 2"<<endl;
}
};

int main(){

BaseClass Base,*BasePointer;
DerivedClass Derived, *DerivedPointer;
DerivedClass2 Derived2;

BasePointer=&Base;
BasePointer->Display();

BasePointer=&Derived;
BasePointer->Display();

BasePointer=&Derived2;
BasePointer->Display();

cout<<"Now Using DerivedClass Pointer"<<endl;

DerivedPointer=&Derived;
DerivedPointer->Display();

DerivedPointer=&Derived2;
DerivedPointer->Display();

return 0;
}

Output:

You are accessing Display Function of Superclass


You are accessing Display Function of Derived Class
You are accessing Display Function of Derived Class 2
Using DerivedClass Pointer
You are accessing Display Function of Derived Class
You are accessing Display Function of Derived Class 2

Date:
2016

29 Aug

Q8. Write a C++ program to implement the concept of Method


Overloading
#include<iostream>
#include<stdlib.h>
using namespace std;
class area{
public:
void objarea(float radius){
cout<<"Area is : "<<3.14*radius*radius;
}
void objarea(int sqlength){
cout<<"Area is : "<<sqlength*sqlength<<endl;
}
void objarea(int length,int breadth){
cout<<"Area is : "<<length*breadth<<endl;
}
};
int main(){
int num;
do{
cout<<"Enter the Choice"<<endl;
cout<<"1. Area of Rectangle"<<endl;
cout<<"2. Area of Square"<<endl;
cout<<"3. Area of Circle"<<endl;
cout<<"4. exit"<<endl;
cin>>num;

switch(num){
case 1: area Rectangle;

int length,breadth;
cout<<"Enter Length and Breadth of Rectangle"<<endl;
cin>>length>>breadth;
Rectangle.objarea(length,breadth);
break;
case 2: area Square;
int sqlength;
cout<<"Enter Length of Square"<<endl;
cin>>sqlength;
Square.objarea(sqlength);
break;
case 3: area Circle;
float radius;
cout<<"Enter Radius of Circle followed by decimals"<<endl;
cin>>radius;
Circle.objarea(radius);
break;
case 4: exit(1);
break;
default: cout<<"Enter Valid Input!"<<endl;
}
}while(num<5);

return 0;
}
Output:
Enter the Choice
1. Area of Rectangle

2. Area of Square
3. Area of Circle
4. exit

1
Enter Length and Breadth of Rectangle
10 20
Area is : 200
Enter the Choice
1. Area of Rectangle
2. Area of Square
3. Area of Circle
4. exit
2
Enter Length of Square
10
Area is : 100
Enter the Choice
1. Area of Rectangle
2. Area of Square
3. Area of Circle
4. exit
4

You might also like