Unit 5: Pointer & Virtual Functions
Topics:
● Pointers to objects
● Pointer to Derived Classes
● Virtual Functions
● Pointer to Virtual Functions
● ‘this’ Pointer
5.1 Pointers to objects
● A pointer is a variable that stores the memory address of another variable( or
object) as its value. A pointer aims to point to a data type which may be int,
character, double, etc. Pointers to objects aim to make a pointer that can pierce
the object, not the variables. Pointer to object in C refers to penetrating an object.
There are two approaches by which you can pierce an object. One is directly and
the other is by using a pointer to an object in c.
● A pointer to an object in C is used to store the address of an object. For creating
a pointer to an object in C, we use the following syntax
● classname * pointertoobject;
● For storing the address of an object into a pointer in c, we use the following
syntax
● pointertoobject = & objectname;
● The below syntax can be used to store the address in the pointer to the object.
After storing the address in the pointer to the object, the member function can be
called using the pointer to the object with the help of an arrow driver.
Example
● 1. In the below illustration, a simple class namedMy_Class is created. An object
of the class is defined as a named object. Then a pointer is also defined named
p. In the program given below, it's shown how we can pierce the object directly
and how we can use the pointer to pierce the object directly.
// Example using an object pointer.
Page | 1
#include <iostream>
using namespace std;
class My_Class {
int num;
public:
void set_number(int value) {num = value;}
void show_number();
};
void My_Class::show_number()
{
cout << num << "\n";
}
int main()
{
My_Class object, *p; // an object is declared and a pointer to it
object.set_number(1); // object is accessed directly
object.show_number();
p = &object; // the address of the object is assigned to p
p->show_number(); // object is accessed using the pointer
return 0;
}
Output:
1
1
Example 2. In the below example, we used a pointer to an object and an arrow operator.
#include<iostream>
using namespace std;
class Complex{
int real, imaginary;
Page | 2
public:
void get_Data(){
cout<<"Here the real part is "<< real<<endl;
cout<<"Here the imaginary part is "<< imaginary<<endl;
}
void set_Data(int x, int y){
real = x;
imaginary = y;
}
};
int main(){
Complex *ptr = new Complex;
ptr->set_Data(1, 54);
ptr->get_Data();
// Array of Objects
Complex *ptr1 = new Complex[4];
ptr1->set_Data(1, 4);
ptr1->get_Data();
return 0;
}
Output:
Here the real part is 1
Here the imaginary part is 54
Here the real part is 1
Here the imaginary part is 4
5.2 Pointer to Derived Classes
● Pointers to objects of the base class are type compatible with the pointers to
objects of a deduced class. thus a single pointer variable can be made to point to
the objects belonging to different classes lets see in Example if B is a base class
and D is a deduced class from B, also a pointer declare as a pointer to B can
also be a pointer toD.
Page | 3
● consider the following declarations
B *cptr;
B b;
D d;
cptr=&b;
● we can make in the above example cptr to point to the object d as follows
cptr=&d; // cptr points to object d
This is perfectly valid with c++ language because d is an object derived from the
class B
● Still these is a problem in using cptr to pierce the public of the deduced classD.
using cptr we can pierce only those members which are inherited from B and not
the member that firstly belongs to D. in case a member of D class has the same
name as one of the members of class B, also any reference to that member by
cptr variable will always pierce the base class member.
● Althought c language permits a base pointer to point to any object deduced from
the base the pointer can not be directly used to pierce all the members of the
deduced class. we may have to use another pointer declared as pointer to the
deduced type.
● let us take example of how pointers to a derived object are used
POINTER TO DERIVED OBJECTS #include<iostream>
using namespace std;
class BC
{
public:
int b;
void show()
{
Page | 4
cout << "b=" << b << "\n";
}
};
class DC: public BC
{
public:
int d;
void show()
{
cout << "b=" << b << "\n";
cout << "d=" << d << "\n";
}
};
int main()
{
BC *bptr; // base pointer
BC base;
bptr=&base; //base address
bptr->b=100; // access BC via base pointer<
cout << "bptr points to base object \n";
bptr->show();
//derived class
DC derived;
Page | 5
bptr=&derived; // address of derived object
bptr->b=200; // access DC via base pointer
/* bptr->d=300; */ // won't work
cout << "bptr now points to derived object \n";
bptr->show(); //bptr now points to derived object
/* accessing d using a pointer of type derived class DC*/
DC *dptr; // derived type pointer
dptr=&derived;
dptr->d=300;
cout << "dptr is derived type pointer \n";
dptr->show();
cout << "using ((DC*)bptr)\n";
((DC*)bptr)->d=400;
((DC*)bptr)->show();
output:
bptr points base object
b=100
bptr now points to derived object
b=200
dptr is derived type pointer
b=200
Page | 6
d=300
using((DC?)bptr)
b=200
d=400
● Note: we have used the statement
bptr->show();
so two times first when bptr points to the base object, and second when bptr is
made to point to the deduced object. but both times, it executed the BCshow()
function and displayed the content of the base object. How ever the statements
● dptr->show();
((DC *)bptr)->show(); // cast bptr to DC type
Display the contents of the deduced object. This shows that, although a base
pointer can be made to point to any number of deduced objects, it can not
directly pierce the members defined by a deduced class.
5.3 Virtual Functions
● A virtual function is a member function which is declared within a base class and
isre-defined( overridden) by a deduced class. When you relate to a deduced
class object using a pointer or a reference to the base class, you can call a virtual
function for that object and execute the deduced class’s interpretation of the
function.
● Virtual functions insure that the correct function is called for an object, anyhow of
the type of reference( or pointer) used for function call.
● They're substantially used to achieve Runtime polymorphism
● Functions are declared with a virtual keyword in base class.
● The resolving of function call is done at runtime.
Rules for Virtual Functions
● Virtual functions can not be static.
● A virtual function can be a friend function of another class.
● Virtual functions should be penetrated using pointer or reference of base class
type to achieve runtime polymorphism.
● The prototype of virtual functions should be the same in the base as well as
deduced class.
Page | 7
● They're always defined in the base class and overridden in a deduced class. It
isn't obligatory for the deduced class to stamp( orre-define the virtual function), in
that case, the base class interpretation of the function is used.
● A class may have a virtual destructor but it can not have a virtual constructor.
Compile time (early binding) VS runtime (late binding) behavior of Virtual Functions
● Consider the following simple program showing runtime behavior of virtual
functions.
#include<iostream>
using namespace std;
class base {
public:
virtual void print()
{
cout << "print base class\n";
}
void show()
{
cout << "show base class\n";
}
};
class derived : public base {
public:
void print()
{
cout << "print derived class\n";
}
void show()
{
cout << "show derived class\n";
}
};
Page | 8
int main()
{
base *bptr;
derived d;
bptr = &d;
// Virtual function, binded at runtime
bptr->print();
// Non-virtual function, binded at compile time
bptr->show();
return 0;
}
Output:
● print derived class
● show base class
5.4 Pointer to Virtual Functions
● If you have a struct like this one
● struct A{ void func();};
● and a reference like this one
● A & a;
● you can get a pointer to its func system like this
● someMethod( & Afunc);
Now what if that method is virtual and you don't know what it is at run-time? Why
can't you get a pointer like this?
someMethod(&a.func);
Is it possible to get a pointer to that method?
● Pointers to members take into account the virtuality of the functions they point at.
For example:
● #include <iostream>
struct Base {
Page | 9
virtual void f()
{
std::cout << "Base::f()" << std::endl;
} };
struct Derived:Base
{
virtual void f()
{
std::cout << "Derived::f()" << std::endl;
} };
void SomeMethod(Base& object, void (Base::*ptr)())
{
(object.*ptr)();
}
int main()
{
Base b;
Derived d;
Base* p = &b;
SomeMethod(*p, &Base::f); //calls Base::f()
p = &d;
SomeMethod(*p, &Base::f); //calls Derived::f()
}
● Outputs:
Base::f()
Derived::f()
5.5 ‘this’ Pointer
In C programming, this is a keyword that refers to the current case of the class. There
can be 3 main uses of this keyword in C.
● It can be used to pass the current object as a parameter to another system.
● It can be used to relate to the current class case variable.
● It can be used to declare indicator.
this Pointer Example
Page | 10
Let's see the example of this keyword in C++ that refers to the fields of current class.
#include <iostream>
using namespace std;
class Employee {
public:
int id; //data member (also instance variable)
string name; //data member(also instance variable)
float salary;
Employee(int id, string name, float salary)
this->id = id;
this->name = name;
this->salary = salary;
void display()
cout<<id<<" "<<name<<" "<<salary<<endl;
Page | 11
};
int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of
Employee
Employee e2=Employee(102, "Nakul", 59000); //creating an object of
Employee
e1.display();
e2.display();
return 0;
Output:
101 Sonoo 890000
102 Nakul 59000
Page | 12