Pointers and Virtual Functions Final 1
Pointers and Virtual Functions Final 1
2
Course Outcomes
CO Course Outcome
Number
CO1 Understand the concepts of object-oriented programming
including programming process and compilation process.
CO2 Apply different techniques to decompose a problem and
programmed a solution with its sub modules.
CO3 Analyze and explain the behavior of simple programs involving
the programming addressed in the course.
CO4 Implement and evaluate the programs using the syntax and
semantics of object-oriented programming.
CO5 Design the solution of real-world problems in order to
determine that the program performs as expected.
3
Scheme of Evaluation
4
Contents
• Declaring & initializing pointers
• Virtual function
5
Introduction of Pointers
• Pointer is a variable (like int, float, char,...) which holds
address of another variables.
• Pointer is the most important concept in case of System
programming or CORE programming coz it allows direct
access to memory locations
e.g.:-
1. int a=10;
2. int *pa=&a;
3. cout<<*pa;
6
Course Objectives
• To understand the basics of Pointers in C++
Programming.
• To apply virtual functions in programming languages for
modeling real world problems.
• To apply the concept of Dynamic Memory Allocation.
Declaring Pointer
Data-type *name;
• * is a unary operator, also called as indirection operator.
• * is used to declare a pointer and also to dereference a
pointer.
• When you write int *,
• compiler assumes that any address that it holds points
to an integer type.
• m= &count;
• it means memory address of count variable is stored into
m.
8
Initializing Pointer
Int *ptr;
• declaring variable ptr which holds the value at
address of int type
int val =1;
• assigning int the literal value of 1
ptr=&val;
• dereference and get value at address stored in ptr
int deref =*ptr
• cout<< deref;
•Output will be 1
Benefits of Pointer
10
Pointer Types
• Pointer
• C++ has pointer types for each type of object
• Pointers to int objects
• Pointers to char objects
• Pointers to user-defined objects
(e.g., RationalNumber)
• Even pointers to pointers
• Pointers to pointers to int objects
Pointer Variable
Examples:
int *n;
RationalNumber *r;
int **p; // pointer to pointer
Address Operator &
• The "address of " operator (&) gives the memory
address of the variable
• Usage: &variable_name
… … 100 … … …
a
int a = 100;
//get the value,
cout << a; //prints 100
//get the memory address
cout << &a; //prints 1024
Address Operator &
Memory address: 1020 1024 1032
… 88 100 … … …
a b
#include <iostream>
using namespace std; Result is:
void main(){ The address of a is: 1020
The address of b is: 1024
int a, b;
a = 88; b = 100;
cout << "The address of a is: " << &a <<
endl;
cout << "The address of b is: " << &b << endl;
Pointer Variables
Memory address: 1020 1024 1032
… 88 100 … 1024 …
a p
int a = 100; Result is:
int *p = &a; 100 1024
cout << a << " " << &a <<endl; 1024 1032
cout << p << " " << &p <<endl;
58 58 58
Dereferencing Operator *
• We can access to the value stored in the variable pointed to
by using the dereferencing operator (*),
… 88 100 … 1024 …
a p
int a = 100;
int *p = &a; Result is:
cout << a << endl; 100
cout << &a << endl; 1024
cout << p << " " << *p << endl; 1024 100
cout << &p << endl; 1032
Points to remember
• Declaring a pointer means only that it is a pointer: int *p;
• Don’t be confused with the dereferencing operator, which is also
written with an asterisk (*). They are simply two different tasks
represented with the same sign
int a = 100, b = 88, c = 8;
int *p1 = &a, *p2, *p3 = &c;
p2 = &b; // p2 points to b
p2 = p1; // p2 points to a
b = *p3; //assign c to b
*p2 = *p3; //assign c to a Result is:
888
cout << a << b << c;
Pointer Example
Memory Layout
The code
Box diagram
void doubleIt(int x,
main
int * p)
p
{ a 16 (8200)
8192
*p = 2 * x; doubleIt
} x
(8196)
9
int main(int argc, const
char * argv[])
a
{
doubleIt (8192)
16 main
int a = 16;
doubleIt(9, &a);
x 9
return 0;
} a gets 18 p
Pointer Example
#include <iostream>
Let’s figure out:
using namespace std;
int main (){ value1==? / value2==?
int value1 = 5, value2 = 15; Also, p1=? p2=?
int *p1, *p2;
p1 = &value1; // p1 = address of value1
p2 = &value2; // p2 = address of value2
*p1 = 10; // value pointed to by p1=10
*p2 = *p1; // value pointed to by p2= value // pointed to by p1
p1 = p2; // p1 = p2 (pointer value copied)
*p1 = 20; // value pointed to by p1 = 20
cout << "value1==" << value1 << "/ value2==" << value2;
return 0;
}
Pointer Example
int a = 3;
char s = ‘z’;
double d = 1.03;
int *pa = &a;
char *ps = &s;
double *pd = &d;
% sizeof returns the # of bytes…
cout << sizeof(pa) << sizeof(*pa)
<< sizeof(&pa) << endl;
cout << sizeof(ps) << sizeof(*ps)
<< sizeof(&ps) << endl;
cout << sizeof(pd) << sizeof(*pd)
<< sizeof(&pd) << endl;
Reference Variables
A reference is an additional name to
an existing memory location
Pointer: Reference:
x 9 x 9
re
f
re
f
int x = 9;
int x=9;
int &ref = x;
int *ref;
ref = &x;
Reference Variables
int m = 10;
int &j = m; // j is a reference variable
cout << “value of m = “ << m << endl;
//print 10
j = 18;
cout << “value of m = “ << m << endl;
// print 18
Reference Variables
1000
1004
1008
1012
1016
Pointers and Arrays
#include <iostream>
using namespace std;
Result:
Address of a[0]: 0x0065FDE4
Name as pointer: 0x0065FDE4
Dereferencing An Array Name
This element is
called a[0]
or *a
#include <iostream>
a[0] 2 using namespace std;
a void main(){
a[1] 4 int a[5] = {2,4,6,8,22};
a[2] cout << *a << " "
6
<< a[0];
a[3] 8 } //main
a[4] 22
a
Array Names as Pointers
To access an array, any pointer to the first element can be
used instead of the name of the array.
We could replace *p by *a
#include <iostream>
a p using namespace std;
void main(){
a[0] 2 int a[5] = {2,4,6,8,22};
22
a[1] 4 int *p = a;
cout << a[0] << " "
a[2] 6
<< *p;
a[3] 8 }
a[4] 22
a
Multiple Array Pointers
Both a and p are pointers to the same array.
#include <iostream>
a[0] using namespace std;
a[0] 22
2 p void main(){
44 int a[5] = {2,4,6,8,22};
a[1] 4 int *p = &a[1];
a[2] 6 cout << a[0] << " "
<< p[-1];
a[3] 8 p[0] cout << a[1] << " "
a[4] << p[0];
22 }
Pointer Arithmetic
Given a pointer p, p+n refers to the element that is
offset from p by n positions.
a 2 p - 1
a + 1 4 p
a + 2 6 p + 1
a + 3 8 p + 2
a + 4 22 p + 3
Dereferencing Array Pointers
a[0] or *(a + 0) 2 a
a[1] or *(a + 1) 4 a + 1
a[2] or *(a + 2) 6 a + 2
a[3] or *(a + 3) 8 a + 3
a[4] or *(a + 4) 22 a + 4
int oned[12];
for(int i=0; i<3; i++){
for(int j=0; j<4 ; j++)
oned[i*4+j] = twod[i][j];
}
Virtual function
• A virtual function a member function which is
declared within base class and is re-defined
(Overriden) by 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
function.
• They are mainly used to achieve run time
polymorphism.
• Functions are declared with a virtual keyword in base
class.
37
Rules for Virtual
function
• They Must be declared in public section of class.
• Virtual functions cannot be static and also cannot be
a friend function of another class.
• Virtual functions should be accessed using pointer or
reference of base class type to achieve run time
polymorphism.
• The prototype of virtual functions should be same in
base as well as derived class.
• They are always defined in base class and
overridden in derived class.
38
NOTE: If we have created virtual function in base
class and it is being overridden in derived class then
we don’t need virtual keyword in derived class,
functions are automatically considered as virtual
functions in derived class.
39
Program to implement virtual function
#include <iostream>
using namespace std;
class base {
public:
virtual void print()
{
cout << "print base class" << endl;
}
void show()
{
cout << "show base class" << endl;
}
}; 40
class derived : public base {
public:
void print()
{
cout << "print derived class" << endl;
}
void show()
{
cout << "show derived class" << endl;
}
};
41
int main()
{
base* bptr;
derived d;
bptr = &d;
// virtual function, binded at runtime
bptr->print();
// Non-virtual function, binded at compile time
bptr->show();
}
42
Output
print derived class
show base class
43
Frequently Asked question
Q1 What is a pointer?
A pointer is a variable whose value is the address of another
variable, i.e., direct address of the memory location. Like any
variable or constant, you must declare a pointer before using it to
store any variable address. The general form of a pointer variable
declaration is −
• type *var-name;
Q2 What is the use of virtual?
You use virtual functions when you want to override a certain
behavior (read method) for your derived class rather than the one
implemented for the base class and you want to do so at run-time
through a pointer to the base class.
44
Q3 What is run time polymorphism and how to achieve it ?
Virtual functions in C++ use to create a list of base class
pointers and call methods of any of the derived classes
without even knowing kind of derived class object. Virtual
functions are resolved late, at runtime. ...
Runtime polymorphism can be achieved only through a
pointer (or reference) of base class type.
45
Assessment Questions:
1. Which of the following is true about virtual functions in C++.
A Virtual functions are functions that can be overridden in derived class with the same signature.
B Virtual functions enable run-time polymorphism in a inheritance hierarchy.
C If a function is 'virtual' in the base class, the most-derived class's implementation of the
function is called according to the actual type of the object referred to, regardless of the declared
type of the pointer or reference. In non-virtual functions, the functions are called according to the
type of reference or pointer.
D. All of the above
Ans:-D
2. Which of the following is the correct way to declare a pointer ?
A. int *ptr
B. int ptr
C. int &ptr
D. All of the above
Ans:-A
46
Discussion forum.
Can a virtual function be const? Why virtual function
is used in C++?
https://www.youtube.com/watch?v=SF8HbxDbNr0&t=14s
47
REFERENCES
Reference Books
[1] Programming in C++ by Reema Thareja.
[2] Programming in ANSI C++ by E.
Balaguruswamy, Tata McGraw Hill.
[3] Programming with C++ (Schaum's Outline
Series) by Byron Gottfried Jitender
Chhabra, Tata McGraw Hill.
Websites:
• https://www.geeksforgeeks.org/virtual-function
-cpp/
YouTube Links:
• https://www.youtube.com/watch?v=SF8HbxDb
Nr0&t=14s
48
THANK YOU