In: Computer Science
1. In c++, Class D is derived from class B. The class D does not contain any data members of its own . Does the class D require constructor? If yes, why? Explain with the help of a code example.
2. State true or false, giving proper reasons[3,5]
(a) Virtual functions are used to create pointer to base
class.
(b) A pointer to base class cannot be made to point to objects of
derived class.
(c) Defining a derived class requires some changes in base
class.
(d) Inheritance helps in making a general class into a more
specific class.
3. When do we make a virtual function pure? What are the implications of making a pure virtual function?
Answer 1 - Yes class D requires constructor even if it doesn’t contain any data member of its own. This is beacuase Base class constructor is always called from the base class constructor to provide the values to the base class constructor. Example;-
#include <iostream>
using namespace std;
class alpha{
int p;
public:
alpha(int i)
{
p=i;
cout<<"alpha initialized"<<endl;
}
void show_p(void){
cout<<"p="<<p<<endl;}
};
class beta{
float q;
public:
beta(float j){
q=j;
cout<<"beta initialized"<<endl;
}
void show_q(void){
cout<<"q="<<q<<endl;
}
};
class gamma: public beta , public alpha{
int x,y;
public:
gamma(int a, float b, int c, int d):
alpha (a),beta(b){
x =c;
y =d;
cout<<"gamma initialized"<<endl;
}
void show_xy(void)
{
cout<<"x="<<x<<endl;
cout<<"y="<<y<<endl;
}
};
int main( ){
gamma g(4,10,50,20);
cout<<"\n";
g.show_p( );
g.show_q( );
g.show_xy( );
}
Answer 2 -
2(a) - True : Virtual functions are used to create a list of base class pointers and call methods of any of the derived classes without even knowing the kind of derived class object
2(b) - False : A derived class includes everything that is in the Base class and thus Base class can access all those fields and methods in Base class which are common to Base class and derived class
2(c) - False : Derived class only use or inherits the properties(fields and methods) from the Base class, base class doesn't require any changes.
2(d) - True : Base class provides the generic definations to the methods or simply they provide their declaration, with the help of inheritance Derived/child classes provides definations to the base class methods according to their functionality
Answer 3 : A pure virtual function is useful when we have a function that we want to put in the base class, but only the derived classes know what it should return. A pure virtual function makes it so the base class can not be instantiated, and the derived classes are forced to define these functions before they can be instantiated. This helps ensure the derived classes do not forget to redefine functions that the base class was expecting them to.