Unit 3 Inheritance
Unit 3 Inheritance
ABSTRACT CLASSES
An abstract class is a class not used for creating objects. It is designed only to act as a base class.
These classes are similar to a skeleton on which new classes are designed. These classes contain pure
virtual functions.
A pure virtual function (or abstract function) in C++ is a virtual function for which we can have an
implementation, But we must override that function in the derived class, otherwise, the derived class
will also become an abstract class. A pure virtual function is declared by assigning 0 in the
declaration.
abstract class must include at least one pure virtual function, it may also have fully defined member
functions.
Syntax:
class classname //abstract class
{
//data members
public:
//pure virtual function
/* Other members */
};
Virtual Function
A virtual function (also known as virtual methods) is a member function that is declared within a base class
and is re-defined (overridden) by a derived class. When you refer to a derived class object using a pointer or a
reference to the base class, you can call a virtual function for that object and execute the derived class’s
version of the method.
• Virtual functions ensure that the correct function is called for an object, regardless of the type of reference
(or pointer) used for the function call.
• They are mainly used to achieve Run time polymorphism.
• Functions are declared with a virtual keyword in a base class.
• The resolving of a function call is done at runtime.
Rules for Virtual Functions
The rules for the virtual functions in C++ are as follows:
#include<iostream.h>
using namespace std; In the above example, variables p, d, and c are variables of
int p;
type int, float, and char, respectively.
float d; Pointer pt is a pointer of type void. These entire variables are
char c;
declared before main(). The pointer is initialized with the
void *pt = &p; // pt points to p
address of integer variable p.
int main () The statement *(int *) pt = 12 assigns the integer value 12 to
{
pointer pt, that is, to a variable p.
*(int *) pt = 12; The contents of the variable p are displayed using the
cout<<“\n p=”<<p;
succeeding statement.
pt = &d; // pt points to d The declaration *(int *) tells the compiler that the value
*(float *)pt = 5.4;
assigned is of integer type.
cout<<“\n r=”<<d; Thus, the assignment of float and char type is carried out.
pt=&c; // pt points to c The statements *(int *) pt = 12, *(float *) pt = 5.4, and
*(char* )pt=‘S’;
*(char*) pt = ‘S’ help the compiler exactly determine the
cout<<“\n c=”<<c;
size of data type.
}
cout<<t.num<<"\n"<<num;
if (t.num<num)
#include<iostream>
using namespace std; return t;
} }
458 152