Inheritance, Virtual Functions and Polymorphism-1

Estudies4you

Inheritance, Virtual Functions and Polymorphism

Q1. What is Inheritance?
Answer:
Inheritance is an object-oriented technique used for deriving the features of one class into another class. It allows to build a hierarchy of classes such that, starting from a most general class to a most specific class. The class which is inherited is called as a ‘base’ class or a ‘parent’ class and the class which inherits a base class is called a ‘derived’ class or a ‘child’ class. The base class contains features that are common to all objects that are derived from it. Whereas, the derived class includes its base class features as well as its own features. Moreover, the derived class may in-turn become the base class and can be inherited by another derived class.

Q2. Define Base class and Derived class.
Answer:
Base Class
Base class is a class from which other classes can be inherited. It is also called as a ‘super class’ or a ‘parent class’. This class does not have any knowledge about its sub-classes. It is constant and cannot be changed. Any number of classes can be derived from a base class.

Derived Class
Derived class is a class that is inherited from a base class. It can inherit all the properties and behaviour of the base class. It contains additional members apart from having base class members. It is also called as a ‘subclass’ or a ‘child class’.

Syntax:
class Baseclass
{
--------------------
};
class Derivedclass: AccessSpecifier Baseclass
{
--------------------
};

Q3. What are Destructors?
Answer:
A destructor is a special member function that is used to destroy the objects created by constructor. It takes the same name as the class but with a ‘tilde’ (~) at the beginning. It doesn’t have any return type. It is called automatically at the end of the program execution to free up the acquired storage.
Memory allocation is done by using new operator in a constructor whereas delete operator is used in a destructor to deallocate the previously allocated memory.

Q4. Explain about virtual Base class.
Answer:
C++ has introduced the keyword ‘virtual’ to avoid the ambiguity that takes place by multipath inheritance. When the word virtual is used before the name of a class, it specifies that the class is virtual and indicates the compiler to take some essential caution in order to prohibit the duplication of member variables. Always a base’class is declared as virtual, because it is the class from which other classes are derived. Thus, virtual base class is a class in which virtual keyword is placed before the name of base class while it is inherited. Following example illustrates the syntax for declaring Virtual Base classes.

To Top