In: Computer Science
1 What is a pure virtual function? Why would you define a pure virtual function? Give an example of a pure virtual function.
2 When a function has an object parameter that it doesn't
modify,
what is the best way to declare the parameter (in the
function
signature), and why?
3 Show an example using a function with a string object
parameter.
a) When a class has objects as data members, why should
its
constructors use initialization lists (member and initializer
syntax) vs. assignment to the members in the body of the
ctor?
b) Name two cases where you *must* use initialization lists
in
constructors (as opposed to assignment in the ctor body).
4 When a function has an object parameter that it doesn't
modify,
what is the best way to declare the parameter (in the
function
signature), and why?
Show an example using a function with a string object
parameter.
Pure virtual function:
It is a type of virtual function whose initialization is done with zero, a pure virtual function is not defined in the base class as it is redefined in the derived class. A base class is said to be an abstract class.
A virtual keyword is used to define a pure virtual function.
Syntax:
class Parent
{
public:
virtual void see() = 0;
};
Pure virtual function is basically used to create abstract class. A class with at least one pure virtual function is an abstract class.
Also, an object of an abstract class cannot be created, and the definition of a pure virtual function is given in the derived class. Hence, an object of the derived class is used to call a pure virtual function.
Example:
//header file declared
#include <iostream>
//namespace used
using namespace std;
//base class
class Parent
{
//access modifier
public:
//declaration of pure virtual function
virtual void see() = 0;
};
//inheritance
class Child : public Parent
{
//access modifier
public:
//definition of pure virtual function
void see()
{
//displaying message
cout<<"pure virtual function is defined in derived class";
}
};
//main function
int main()
{
//creating object of derived class
Child ob;
//calling of pure virtual function
ob.see();
return 0;
}
Output: