How to use pure virtual function in C++
#include<iostream> //header file
using namespace std; // header file
class shape // creating class of name shape
{
protected: // access specifier
float dim; // protected variable of data type float of name dim is declared
public: // access specifier
void getdim() // member function in public access specifier
{
cin>>dim;
}
virtual float caldata()=0; // pure virtual function declaration
}; //end of class shape (end of class should be by the semicolon)
class square: public shape //class square derived from class shape
{
public: // access specifier
float caldata() // function definition
{
return dim*dim; //function body
}
}; //end of class square
class circle: public shape //class circle derived from class shape
{
public: // access specifier
float caldata() // function definition
{
return 3.14*dim*dim; //function body
}
}; //end of class circle
int main()
{
square s; // object created of class square
cout<<"Enter length: "<<endl; // prints enter length statement
s.getdim(); // getdim function called of class square
cout<<"Area of square: "<<s.caldata()<<endl; // prints Area of square and the value of s.caldata() function
circle c; // object created of class square
cout<<"Enter radius: "<<endl; //prints Enter radius statement and
c.getdim(); // getdim() function called of class circle
cout<<"Area of circle: "<<c.caldata()<<endl; //prints area of circle and the value of caldata() function
}
Output:
Enter length:
23
Area of square: 529
Enter radius:
11
Area of circle: 379.94
Comments
Post a Comment