Introduction
Syntax
virtual return_type function_name()=0;
Example
virtual void area()=0;
};
class rectangle : public shape
{
int length,breadth;
public:
rectangle(int l,int b)
{
length=l;
breadth=b;
}
void showrect()
{
cout<<"\nLength "<
cout<<"\nBreadth "<
}
void area()
{
int ar;
ar=length*breadth;
cout<<"\nArea of rectangle is "<
}
};
class square : public shape
{
int side;
public:
square(int s)
{
side=s;
}
void showsquare()
{
cout<<"\nSide : "<
}
void area()
{
int ar;
ar=side*side;
cout<<"\nArea of Square : "<
}
};
void main()
{
clrscr();
cout<<"\nRECTANGLE";
rectangle rect(4,5);
rect.showrect();
rect.area();
cout<<"\nSQUARE";
square sq(9);
sq.showsquare();
sq.area();
}
Output
RECTANGLE
Length 4
Breadth 5
Area of rectangle is 20
SQUARE
Side : 9
Area of Square : 81
A "Pure Virtual Function" is a virtual function that is declared as "Virtual" in the base class and overridden in the derived class. A "Pure Virtual Function" does not have a body or definition in the containing class. To declare a "Pure Virtual Function", the function declaration is terminated by adding a "()=0" at the end to denote that the function has no body. A class that has at least one Pure Virtual Function is called an "Abstract Class"(See previous posts for an explanation on abstract class). All the classes that inherit from an "Abstract" Class must define or override all the pure virtual functions. If a child class fails to override a pure virtual function of the parent class the compiler will return an error.
Syntax
virtual return_type function_name()=0;
Example
#include
#include
class shape
{virtual void area()=0;
};
class rectangle : public shape
{
int length,breadth;
public:
rectangle(int l,int b)
{
length=l;
breadth=b;
}
void showrect()
{
cout<<"\nLength "<
cout<<"\nBreadth "<
}
void area()
{
int ar;
ar=length*breadth;
cout<<"\nArea of rectangle is "<
}
};
class square : public shape
{
int side;
public:
square(int s)
{
side=s;
}
void showsquare()
{
cout<<"\nSide : "<
}
void area()
{
int ar;
ar=side*side;
cout<<"\nArea of Square : "<
}
};
void main()
{
clrscr();
cout<<"\nRECTANGLE";
rectangle rect(4,5);
rect.showrect();
rect.area();
cout<<"\nSQUARE";
square sq(9);
sq.showsquare();
sq.area();
}
Output
RECTANGLE
Length 4
Breadth 5
Area of rectangle is 20
SQUARE
Side : 9
Area of Square : 81
Thanks so much for the explanation! Very nice, and good to pick up concept of pure virtual function. This is a good link too:
ReplyDeletehttp://www.programmerinterview.com/index.php/c-cplusplus/pure-virtual-function/