What is pure virtual function? Explain with suitable example

Q.3) a)What is pure virtual function? Explain with suitable example.

Ans.

In many situations, when complete definition of a function is not defined in the base class or there is a condition that derived class must override the particular function. In such case we need to declare a function as pure virtual function.

A pure virtual function has no definition in the base class. Syntax for declaring a pure virtual function is as follows:
virtualret_typefun_name(parameter_list)=0;

If the derived class is not providing the definition of pure virtual function then a compile time error will be generated.

A class that contains one or more than one pure virtual function is called as abstract class. We cannot create the object of abstract class.

Example:
#include< iostream>
using namespace std;

classbaseClass
{
public:
virtual void show()=0;
};
classderiveClass: public baseClass
{
public:
void show()
{
cout << "Welcome";
}
};
int main() {

deriveClassobj;
obj.show();

return 0;
}


b.) Explain with example, conversion from class type to built in type.

Ans.

We can overload the casting operator that is used to convert the user defined type to built in type. The general form of an overloaded casting operator is as follows.

operatortype_name
{
Some code here.

}

There are three conditions that need to be satisfied for an overloaded casting operator.

- Overloaded casting operator should not have any return type.
- It cannot take any parameters.
- It should be defined inside a class definition.

Example:

class Distance {
float meter;
public:
Distance() // Default Constructor
{
meter=0;
}
Distance(float m) //two arguements constructor
{
meter=m;
}
operator float() //overloaded casting operator
{
return meter*100; // convert meter into centimeter.
}
};
int main() {

float m;
cout<< "\n Enter distance in meter.";
cin >> m;
Distance dist(m);
float centimeters=dist; // This will call overloaded casting operator

cout << "Converted Distance in Centimeter is: \t" << centimeters << endl;
}
Post your comment