C++ Project File
Topic :- Pointers , Virtual functions
and Polysmorphism
Made by:- Gaganpreet Kaur
Siya
Karanveer Singh
Table of contents :-
➢ Polymorphism
➢ Pointers
➢ Declaring And Initializing Pointers
➢ Manipulation of Pointers
➢ Using Pointer with Arrays and Strings
➢ Pointer And Strings
➢ Pointers this Functions
➢ Pointer to Objects
➢ this Pointer
➢ Pointer to derived Classes
➢ Virtual Functions
➢ Pure Virtual Functions
➢ Virtual constructors and destructors
Polymorphism
Polymorphism is a fundamental concept in object-oriented
programming that allows objects to be treated as instances of their
parent class rather than their actual [Link] simply means “One name ,
multiple forms”.
Polymorphism is of two types and they further have sub types.
Polymorphism
Compile Time Run Time
Object Overloading Function Virtual Functions
Overloading
Compile time & Run time polymorphism
Compile-time polymorphism, Run time polymorphism, also
also known as static known as dynamic
polymorphism, is a feature in polymorphism or late binding,
C++ that allows functions or is a feature of object-oriented
operators to behave differently programming that allows a
based on their arguments. This function to behave differently
is determined during the based on the object that
compilation of the program, invokes it. This is achieved
hence the name. The primary through virtual functions.
mechanisms to achieve
compile-time polymorphism in
C++ are function
overloading and operator
overloading.
Pointers :-
Pointers have a special usage with accessing member, data and
functions in the context of inherited classes and objects.
A pointer is a derived data type that refers to another data
variable by storing the variable's memory address rather than
the data. A pointer variable defines where to get the value of a
specific data variable instead of defining actual data type. Like C
,a pointer variable can also refer to another pointer in C++.
Declaring and initializing pointers:-
The declaration of a pointer variable takes the following form :-
data - type pointer - variable ; Here, Pointer variable is the
name of the pointer and the data type refer to one of the valid
C++ data types such as int , char, float and so on. The data is
followed by an asterisk (*) ,which distinguishes a pointer variable
from other variables to the compiler. A pointer is able to point to
only one data type at at the specific time we can initialize the
pointer variable as follows :
Int*ptr , a ;
ptr =&a ;
The pointer variable, ptr, contains the address of the variable a
.Like C, we use the 'address of 'operator i. e. '& 'to retrieve the
address of a variable. The second statement assigns the address
of variable a to the pointer ptr. We can also use void pointers,
known as generic pointers, which refer to variables of any data
type. Before using void pointers, we must type cast the variables
to specific data types that they point to.
Manipulation of Pointers:-
We can manipulate a pointer with the indirection operator , i.e.,(*)
which is also known as dereference operator. With this operator, we
can indirectly access the data variable content . It takes the following
general form :-
*pointer_variable
Dereferencing a pointer allows us to get the content of the memory
location that the pointer points to. After assigning address of the
variable to a pointer, we may want to change the content of the
variable. Using the dereference operator, we can change the contents
of the memory location.
Pointer Expressions And Pointer Arithmetic:-
C++ allows pointers to perform the following arithmetic operations :-
➢ A pointer can be incremented (++) or decremented (--).
➢ Any integer can be added or subtracted from a pointer.
➢ One pointer can be subtracted from another.
Using Pointers With Arrays And
Strings :-
Pointers is one of the efficient tools to access elements of
an array. Pointers are useful to allocate arrays dynamically ;
we can decide the array size at run time. To achieve this, we
use the functions namely malloc() and challoc().
In, general there are some differences between pointers and
arrays; arrays refers to a block of memory space, whereas
pointers do not refers to any section of memory. The memory
Addresses of arrays cannot be changed, whereas the content
of the pointer variables, such as memory address that it refers
to, cab be changed. Even through there are subtle differences
between pointers and arrays, they have a strong relationship
between them.
Arrays Of Pointers:-
The array of pointers represents a collection of address. By
declaring array of pointers, we can save a substantial amount
of memory space. An array of pointers point to an array of
data items. Each element of the pointer array points to
an item of the data array. Data items can be accessed either
directly or by dereferencing the elements of pointers array
we can reorganize the pointer elements without affecting the
data items.
We can declare an array of pointes as follows:-
int*inarray[10]; this statement declares an array of 10 pointers
each of which points to an integer.
Pointer and String
C++ also allows us to handle the special kind of arrays i.e.
,string with pointers. A string is one dimensional array of
characters, which starts with the index zero and ends with
the null character '\0' in C++.
A pointer variable can access a string by referring to its first character.
There are two ways to assign a value to a string. We can use the
character array or variable of type char* .Let us consider the
following string declarations: char num[]="one";
Const char * numptr="one";
The first declaration creates an array of 4 characters which contains
the characters ,'o','n','e','\o'whereas the second declaration
generates a pointer variable, which points to the first character that is
'o' of the string. There are numerous strings handling functions
available in C++. All of these functions are available in header file
<cstring>.
Pointers To Functions:-
The pointer to functions is known as a callback function. We can
use this function pointers to refer to a function. Using function
pointer, we can allow a C++ program to select a function
dynamically at run time. C++ provides two type of function
pointers; function pointers that point to static member functions
and function pointers that point to non- static members functions.
This two function pointers that points to non- static member
function requires hidden argument. Like other variables, we can
declare a function pointer in C++. It takes the following form:
data_type(*function _name)
Pointers To Objects:-
We have already seen how to use pointer to access the class
member. As stated earlier, a pointer can be a point to an object
created by a class. Consider the following statement:
Item x;
Where item is a class and x is an object defined to be of type item.
Similarly, we can define a pointer it_ptr of type item as follow:
Item *it_ptr;
Object pointers are useful in creating objects at run time. We can also use
an object pointer to access the public members of an object. Consider a
class item defined as follows:
class item
{
int code;
float price;
public:
void getdata (int a, float b)
{
code=a ;
price=b;
}
void show (void)
{
cout << “Code : “ << code << “\n” ;
<< “Price : “ << price << “\n\n”
}
};
Let us declare an item variable x and a pointe ptr to x as follows:
item x;
item *ptr = &x;
The pointer ptr is initialized with the address of x.
We can refer to the member function of item in two ways, one by using
the dot operator and the object, and another by using the arrow
operator and the object pointer. The statements
[Link]( 100,75.50) ;
[Link]() ;
are equivalent to
ptr->getdata(100,75.50);
ptr->show();
since *ptr is an alias of x, we can also use the following method:
(*ptr) .show () ;
The parentheses are necessary because the dot operatorhas higher
precedence than the indirection operator *.
We can also create the objects using pointers and new operator as
follows:
item *ptr = new item;
This statement allocates enough memory for the data members in the
object structure and assigns the address of the memory space to ptr.
Then ptr can be used to refer to the members as shown below:
ptr -> show() ;
If a class has a constructor with arguments and does not include an
empty constructor, then we must supply the arguments when the
object is created.
We can also create an array of objects using pointers. For example, the
statement
item *ptr = new item[10] ; // array of 10 objects
creates memory space for an array of 10 objects of item. Remember, in
such cases, if the class contains constructors, it must also contain an
empty constructors. It must also contain an empty constructor.
this Pointer:-
C++ uses a unique keyboard called this to represent an object that
invokes a member function. this is a pointer that points to the object for
which this function was called. For example, the function call [Link]()
will set the pointer this to the address of the object A. The starting
address is the same as the address of the first variable in the class
structure.
This unique pointer is automatically passed to a member function when
it is called. The pointer this acts as an implicit argument to all the
member functions. Consider the following simple example:
class ABC
{
int a;
……………
……………
};
The private variable ‘a’ can be used directly inside a member function.
like
a =123 ;
We can also use the following statement to do the same job:
this->a =123 ;
Since C++ permits the use of shorthand form a=123, we have not been
using the pointer this explicitly so far. However, we have been
implicitly using the pointer this when overloading the operators using
member function.
Recall that, when a binary operator is overloaded using a member
function, we pass only one argument to the function. The other
argument is implicitly passed using the pointer this. One important
application of the pointer this is to return the object it points to. For
example, the statement
return *this;
Inside a member function will return the object that invoked the
function. This statement assumes importance when we want to
compare two or more objects inside a member function and return the
invoking object as a result. Example :
person & person : : greater(person & x)
{
if [Link] > age
return x; // argument object
else
return *this; // invoking object
}
Suppose we invoke this function by the call
max = [Link](B) ;
The function will return the object B (argument object) if the age of the
person B is greater than that of A, otherwise, it will return the object A
(invoking object) using the pointer this. Remember, the dereference
operator * produces the contents at the address contained in the
pointer. A complete program to illustrate the use of this is given below:
Pointers To Derived classes:-
We can use pointers not only to the base objects of derived classes.
Pointes to objects of base class are type-compatible with pointers to
objects of a derived class. Therefore, a single pointer variable can be
made to point to objects belonging to different classes. For example, if
B is a base class and D is a derived class from B, then a pointer declared
as a pointer to B can also be a pointer to D. Consider a following
declarations:
B *cptr ; // pointer to class B type variable
Bb; // base object
Dd; // derived object
cptr = &b ; // cptr points to object b
We can make cptr to point to the object d as follows:
cptr = &d ; // cptr points to object d
This is perfectly valid with C++ because d is an object derived from class
B.
However, there is a problem in using cptr to access the public members
of the derived class D. Using cptr, we can access only those members
which are inherited from B and not the members that originally belongs
to D. In case a member of D has the same name as one of members of B,
then any reference to that member by cptr will always access the base
class member.
Although C++ permits a base pointer to point to any object derived from
that base, the pointer cannot be directly used to access all the members
of the derived class. We may have to use another pointer declared as
pointer to the derived type.
Virtual Functions:-
When we use the same function name in both the base and derived
classes, the function in base class is declared as virtual using the
keyword virtual proceeding it's normal declaration. When a function
is made virtual, C++ determines which function to use at run time
based on the type of object pointed to by the base pointer, rather
than the type of the pointer. Thus, by making the base pointer to
point to different objects, we can execute different versions of the
virtual function.
One important point to remember is that, we must access virtual
functions through the use of pointer declared as pointer to the base
class.
A function display() is used in all the classes to display the content.
In the main program we create a heterogeneous list of pointers of
type media.
media * list[2] = {& book1 , & tape1};
The base pointers list[0] and list[1] are initialized with the address of
objects book1 and tape1, respectively.
Rules For Virtual Functions:-
When virtual functions are created for implement late binding, we
should observe some basic rules to satisfy the compiler's
requirements :-
➢ The virtual function must be member of some class.
➢ They cannot be static members.
➢ They are accessed by using object pointers.
➢ A virtual function can be a friend of another class.
➢ A virtual function in base class must be defined, even though it
may not be used.
➢ The prototypes of the base glass version of virtual function and all
derived class versions must be identical.
➢ We cannot have virtual constructors, but we can have virtual
destructors.
➢ While a base pointer can point to any type of derived object, the
reverse is not true.
➢ When a base pointer points to a derived class, incrementing or
decrementing it will not make it to point to the next object of the
derived class. Therefore, we should not use this method to move
the pointer to the next object.
➢ If a virtual function is defined in the base class, it needs not be
necessarily redefined in the derived class.
Pure Virtual Functions:-
It is normal practice to declare a function virtual inside the base class
and redefine it in the derived classes . The function inside the base class
is seldom used for performing any task. It only serves as a placeholder.
A 'do-nothing' function may be defined as follows:-
Such functions are called pure virtual functions. The output of program
would be. A pure virtual function is a function declared in a base class
that has no definition relative the base class. In compiler requires each
derived class to either define the function or redeclare it as a pure
virtual function. The main objective of an abstract base class is to
provide some traits to the derived classes and to create a base pointer
required for achieving run time polymorphism.
Virtual Constructors And Destructors:-
"A constructor cannot be virtual". These are some valid reasons that
justify this statement. First, to create an object the constructor of the
object class must be of the same type as the class. But ,this is not
possible with the virtually implemented constructor. Thus, a virtual
constructor itself would not have anywhere is loop up to. As a result, it
is not possible to declare a constructor as virtual.
Consider the following class declarations that made use of destructors:
class A
{
public ;
-A()
(
// Base class destructor
)
};
class B : public A
{
public :
-B()
{
// Derived class destructor
}
};
main()
{
A* ptr = new B() ;
.
.
delete ptr ;
}
In the above class declaration, both base class A and the derived class
B have their own destructors. Now an A class pointer has been
allocated a B class object. When this object pointer is deleted using
the delete operator, it will trigger the base class destructor and the
derived class destructor won't be called at all. This may lead to a
memory leak situation. To make sure that the derived class
destructor is mandatorily called, we must declare the base class
destructor as virtual.
class A
{
public
virtual –A()
{
// Base class destructor
}
};