0% found this document useful (0 votes)
2 views83 pages

Unit 4

This document provides an overview of pointers and polymorphism in C++. It covers the definition and advantages of pointers, pointer arithmetic, and the use of pointers with arrays and strings, as well as the concept of polymorphism, including compile-time and runtime polymorphism. Additionally, it discusses the relationship between base and derived classes in the context of pointers and provides examples of function and operator overloading.

Uploaded by

shwetagarud2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views83 pages

Unit 4

This document provides an overview of pointers and polymorphism in C++. It covers the definition and advantages of pointers, pointer arithmetic, and the use of pointers with arrays and strings, as well as the concept of polymorphism, including compile-time and runtime polymorphism. Additionally, it discusses the relationship between base and derived classes in the context of pointers and provides examples of function and operator overloading.

Uploaded by

shwetagarud2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 83

UNIT- 4

POINTERS and
POLYMORPHISM in C++
Marks:16
Pointer
• Pointer is a variable that contain a memory
address
num 123
numptr 1001

• A pointer is a data type whose value refers to


another value stored elsewhere in computer
memory using its address
Advantages of pointer
1. Allows to pass variables, arrays, functions and
structures as a function arguments
2. Supports dynamic allocation and deallocation
of memory segments
3. Variables can be swapped without physically
moving them
4. Improves efficiency
• Pointer variable consist of two parts:
1. Pointer operator
2. Address operator
Pointer Operator
• Declaring pointer variable:
data_type *ptr_name;

• This tells compiler 3 things about variable


pte_name:
1. * tells that the variable ptr_name is a pointer
variable.
2. Ptr_name needs a memory location
3. Ptr_name points to a variable of type
data_type.
int *p; //integer pointer
float *x; //float pointer
• Pointer Declaration Style
• int* p; int *p; int * p;
• /* Style 1*/ /* Style 2*/ /* Style 3*/

• Multiple Declarations:
• int *p, x, *q;
Address Operator
• & - “Address of” operator
• This unary operator is used to obtain address
of a variable and can only be used with single
variable or single array element.
• It can not be used with constants, whole array
or expressions.
• Unary operators like * and & have higher
precedence over arithmetic operators.
Address Operator
• Initialization of Pointer Variables
• Example:
int quantity;
int *p; /*Declaration*/
p = &quantity; /initialization*/
or
int *p = &quantity;
Chain of Pointers
Address 2 Address 1 Value
P2 P1 variable
void main()
{
int x,*p1,**p2;
x=100;
p1=&x;
p2=&p1;
cout<<“Value=“<<**p2;
}
Pointer Expressions
int x,y;
int *ptr1,*ptr2;
1. ptr1=&x;
2. y=*ptr1;
3. ptr1=&x;
ptr2=ptr1;

All are valid


1. int x; 3. int x;
int x-ptr; char *c-ptr;
x-ptr=&x; c-ptr=&x;
Error: Error:
2. float y;
float *y-ptr;
y-ptr=y;
Error:
Program to display contents of pointer
void main()
{
int x;
int *ptr;
x=10;
ptr=&x;
cout<<“x=“<<x<<“and ptr=“<<ptr;
cout<<“x=“<<x<<“and *ptr=“<<*ptr;
}
O/P: x=10 and ptr=0x24ccfff4
x=10 and *ptr=10
To assign character variable to pointer and display content of
pointer
void main()
{
char x,y;
char *ptr;
x=‘a’;
ptr=&x;
y=*ptr;
cout<<“value of x=“<<x;
cout<<“pointer value=“<<y;
}
O/P: value of x=a
pointer value=a
Program to display address and content of pointer variable

void main()
{
int x;
int *ptr;
x=10;
ptr=&x;
cout<<“value of x=“<<x;
cout<<“contents of ptr=“<<*ptr;
cout<<“address of ptr=“<<ptr;
}
O/P: value of x=10
contents of ptr=10
address of ptr =0x8f95fff4
Assign pointer variable to another pointer
variable and display contents of both
void main()
{
int x;
int *ptr1,*ptr2;
x=10;
ptr1=&x;
Ptr2=ptr1;
cout<<“value of x=“<<x;
cout<<“contents of ptr1=“<<*ptr1;
cout<<“contents of ptr2=“<<*ptr2;
}
O/P: value of x=10
contents of ptr1=10
contents of ptr2=10
Pointer Arithmetic
1. Addition +
2. Subtraction –
3. Incrementation ++
4. Decrementation --
Ptr++: causes pointer to be incremented, but
not by 1
Ptr--: causes pointer to be decremented, but not
by 1
• Integer value uses 2 bytes memory i.e. 2000
and 2001
int value,*ptr;
value=12;
ptr=&value;
ptr++;
printf(“%u”,ptr);
Displays output as 2002
If system uses 4 bytes to store integer then ptr+
+ would resulted in 2004.
Program to display memory address before and
after incrementation
void main()
{
int val;
int *ptr;
ptr=&val;
cout<<“Memory add before incrementation:”<<ptr;
ptr++;
cout<<“Memory add after incrementation:”<<ptr;
}
O/P: Memory add before incrementation:0x8f95fff2
Memory add after incrementation:0x8f95fff4
Addition
void main()
{
int x,*ptr1,*ptr2;
x=10;
ptr1=&x;
ptr2=ptr1+2;
cout<<“value of x=“<<x;
cout<<“Content of ptr1=“<<*ptr1;
cout<<“Address of ptr1=“<<ptr1;
cout<<“Address of ptr2=“<<ptr2;
cout<<“Content of ptr2=“<<*ptr2;
}
Addition
void main()
{
int x,y,*ptr;
x=10;
ptr=&x;
cout<<“value of x=“<<x;
cout<<“Content of ptr=“<<*ptr;
y=*ptr+1;
cout<<“value of y=“<<y;
cout<<“Content of ptr=“<<*ptr;
}
Incrementation
void main()
{
int x,y,*ptr;
x=10;
ptr=&x;
cout<<“value of x=“<<x;
cout<<“Content of ptr=“<<*ptr;
y=++*ptr;
cout<<“value of y=“<<y;
cout<<“Content of ptr=“<<*ptr;
}
Pointers to arrays
int val[20];
int *ptr;
Valid assignment: ptr=&val[0];
Next element is accessed by incrementing ptr
ptr++==val[1];
• Following equalities are valid:
ptr+5==&val[5]
*ptr==val[0]
*(ptr+5)==val[5]
ptr++==&val[1]
Write a program to accept and display 5
elements from array using pointer
void main( ) p=&a[0];
{
cout<<“\n Array
int *p, i;
elements:”;
int a [5];
p = &a[0];
for(i=0; i<5; i++)
cout<<“\nEnter array {
elements:”; cin<<*p;
for(i=0; i<5; i++)
p++;
{
cin>>*p;
}
p++; }
}
for(i=0; i<5; i++) p++;
{ }
if(*p==no)
}
{
if(flag==0)
cout<<“nNumber is
present….”; {
flag=1; cout<<“\nNumber is
break; not present….”;
} }
else getch();
}
{
flag=0;
Pointers to strings
• String is an array of character terminated by a
special character called NULL character.(‘\0’).
• Strings enclosed within double quotes.
• Pointer to string is pointer which is initialized
to base address of first location of string.
• It is character type pointer
• Syntax: Data_type *pointer_variable_name;
• E.g. char *ptr;
e.g. string: char str[10] and pointer: char *ptr;
Then to initialise use:
ptr=str; or ptr=str[0];
• C++ always places ‘\0’ at the end of string.
Finding length of string
• Function strlen(str); will return length of
string.
• Another way:
counter first initializes to 0 and
increment till end of string i.e. till reaches to ‘\0’
void main() while(*p!=‘\0’)
{ {
char *p,str[10]; len=len+1;
int len=0; p++;
clrscr(); }
cout<<“\nEnter cout<<“\nLength of
string:”; string=”<<len;
cin>>str; getch();
p=str; }
Pointers and Objects
• Object can be created as follows:
item x;
Where item is class and x is an object of that
class.
• Similarly pointer can be defined as follows:
item *ptr;
class item void main( )
{ {
int code; clrscr( );
float price;
item m, *z;
public:
z = &m;
void getdata(int a,float b)
{ z->getdata(45, 85.20); //m.
code=a; getdata( );
price=b; z->show( );
} //(*z).show( );
void show() }
{
cout<<“code:”<<code<< “\
nPrice:”<<price;
}
};
item x;
item *ptr=&x;
i.e. pointer is initialized with the address of x.
2 ways to access member functions:
Using dot and arrow operator
x.getdata(10,56.78);
x.show();
ptr->getdata(10,56.78);
ptr->show();
item x;
item *ptr=&x;
Instead of this objects can be created like
item *ptr=new item;
For array of objects:
item *ptr=new item[10];
Pointer to array of objects void main( )
class Maths { {

int n; public: clrscr( ); int val;


void accept( ) Maths *p = new
{cout<<"\nEnter Maths[5];
number:"; Maths *t = p;
cin>>n; for(int i=0; i<5; i++, p++)
} p->accept( );
int cube( ) { for(i=0; i<5; i++)
int c = n*n*n; {val = t->cube( );
return c; cout<<"\nCube:"<<val;
} t++;
}; }}
This Pointer
• Each object maintains a pointer to itself which
is called the “this” pointer.
• Each object can determine it’s own address by
using the “this” keyword.
• E.g. a.max(); will set pointer this to address of
object a.
class ABC
{
int a;
-------
};
We can use a=111; //shorthand method
also can use this->a=111; //not used so far.
One important application is to return object
it points to. E.g. return *this;
person & person::greater(person &x)
{
if(x.age>age)
return x;
else
return *this;
}
Suppose we invoke this function like
max=A.greater(B);
Function will return object B if age of person B is
greater than A otherwise will return object A i.e.
invoking object using this.
Pointer To Derived Class
• A derived class is a class which takes some
properties from its base class.

• It is true that a pointer of one class can point to


other class, but classes must be a base and
derived class, then it is possible.

• To access the variable of the base class, base


class pointer will be used.
• So, a pointer is type of base class, and it can access
all, public function and variables of base class since
pointer is of base class, this is known as binding
pointer.

• In this pointer base class is owned by base class but


points to derived class object.

• Same works with derived class pointer, values is


changed.
implementation of the base class pointer pointing to derived
class
#include <iostream> class DerivedClass : public BaseClass
using namespace std;
{
class BaseClass { public:
public: int var_derived;
int var_base;
void display()
void display() {
{ cout << "Displaying Base class"
cout << "Displaying Base class"
<< "variable var_base: " <<
<< " variable var_base: " << var_base << endl;
var_base << endl; cout << "Displaying Derived "
}
<< " class variable
}; var_derived: "
<< var_derived << endl;
}
};
int main() base_class_pointer->display();
{ DerivedClass*
BaseClass* base_class_pointer; derived_class_pointer;
BaseClass obj_base; derived_class_pointer =
DerivedClass obj_derived; &obj_derived;
base_class_pointer = derived_class_pointer->var_base =
&obj_derived; 9448;
base_class_pointer->var_base = derived_class_pointer->var_derived
34; = 98;
base_class_pointer->display(); derived_class_pointer->display();
base_class_pointer->var_base = return 0;
3400; }
Output:-
Displaying Base class variable var_base: 34
Displaying Base class variable var_base: 3400
Displaying Base class variable var_base: 9448
Displaying Derived class variable var_derived: 98
Polymorphism
• Poly = Many
• Morphism = form
• Thus Polymorphism = Many Forms
• Identically named methods i.e. member
functions having different behavior depending
on the type of object they refer
• Different internal structure with same external
interface
Types of polymorphism
Definition: it is defined as facility to take more
than one form.
Behavior of function depends upon no of and
type of data.
Types:
1. Compile time/early binding/static binding
2. Runtime /late binding/dynamic binding
Compile time polymorphism
• Function overloading and operator overloading
are used in compile time polymorphism.
• Overloaded functions are selected according to
their argument matching strategy
• During compilation process, C++ compiler
determines function call based on parameters
passed and return type.
• Such invocation of function is called early binding
• Higher efficiency and faster function call are the
advantages of static binding
Runtime Polymorphism
• If function name and prototype is same in both
base and derived class then we can not apply static
binding.
• In such cases appropriate member function is
selected while program is running. This is known as
runtime polymorphism.
• Virtual functions are used to achieve runtime
polymorphism.
• Selection of function is done dynamically at
runtime.
Pointers with polymorphism
Q. Can we use base class pointer for accessing
member function of derived class ? Explain with
suitable example.
Ans:
Case 1: A base class pointer can point to object of
same class or derived class.
Case 2: A derived class pointer can not point to object
of base class but it can point to object of same class
• Example case 1:
class baseA
{
--
--
};
class derivedD:public baseA
{
--
--
};
void main()
{
baseA obja;
derivedD objd;
baseA *ptr;
ptr=&obja; //valid,pointer to same class
ptr=&objd; //valid,pointer to derived class
}
• Example case 2:
class baseA
{
--
--
};
class derivedD:public baseA
{
--
--
};
void main()
{
baseA obja;
derivedD objd;
derivedD *ptr;
ptr=&obja; //error, can not point to base class object
ptr=&objd; //valid,pointer to same class object
}
Overloading
• Overloading refers to the use of same thing for
different purposes.
• Compile time polymorphism can be achieved
in two different ways:
1. Function overloading
2. Operator overloading
Function overloading
• Same function name can be used to create
functions that performs many tasks
• Using this, many functions with one function
name but different arguments can be
designed
• Correct function is invoked by checking
number and type of arguments.
• //declarations
int add(int a,int b); //prototype 1
int add(int a, int b, int c); //prototype 2
float add(float a, float b); //prototype 3
float add(int p, float q); //prototype 4
//Function calls
add(15,10.0);
add(15,10);
add(15.7,10.4);
add(15,10,5);
void main()
#include<iostream.h> {
#include<conio.h> float b,h,r,l;
const float pi=3.14; float result;
float area(float n,float b,float h) clrscr();
{ cout<<“\nEnter the Base & Hieght of
float ar; Triangle: \n”;
ar=n*b*h; cin>>b>>h;
return ar; result=area(0.5,b,h);
} cout<<“\nArea of Triangle:
float area(float r) “<<result<<endl;
{ cout<<“\nEnter the Radius of Circle: \n”;
float ar; cin>>r;
ar=pi*r*r; result=area(r);
return ar; cout<<“\nArea of Circle:
} “<<result<<endl;
float area(float l,float b) cout<<“\nEnter the Length & Bredth of
{ Rectangle: \n”;
float ar; cin>>l>>b;
ar=l*b; result=area(l,b);
return ar; cout<<“\nArea of Rectangle:
} “<<result<<endl;
getch();
}
Revision of Constructor Overloading
• When more than one constructor used in
same class, then constructors are overloaded.
Program
#include <iostream>
using namespace std;

class construct int main()


{ {
// Constructor
public: Overloading
float area; // with two different
constructors
// Constructor with no parameters
construct()
// of class name
{ construct o;
area = 0; construct o2( 10, 20);
}
o.disp();
// Constructor with two parameters o2.disp();
construct(int a, int b)
return 1;
{
area = a * b; }
}
Output:
void disp()
{ 0
cout<< area<< endl; 200
}
};
Operator Overloading
• Assigning special meaning to an operator.
• All c++ operators are overloaded except four
given below:
1. Class member operators(. , .*)
2. Scope resolution operator(::)
3. Size operator(sizeof)
4. Conditional operator(?:)
Defining operator overloading
• Operator function is used to describe task i.e. meaning
applied to an operator.
• Syntax:
returntype classname::operator op(arg-list)
{
function body //task defined
}
• return type is the type of value returned by the specified
operation.
• op is the operator being overloaded.
• op is preceded by the keyword operator.
• operator op is the function name.
• Operator function used in class must be either
member function or friend function.
• Basic difference: friend function has only one
argument for unary operator and 2 arguments for
binary operator while member Function has no
arguments for unary operator and only one argument
for binary operator.
• This is because the object used to invoke the
member function is passed implicitly and therefore is
available for the member function.
• E.g. double operator +(double);
double operator -();
friend double operator +(double, double);
friend double operator -(double);
Overloading unary operators
Consider a unary minus operator:
– It takes just one operand.

– It changes the sign of an operand when applied to


a basic data item.

– The unary minus when applied to an object should


change the sign of each of its data items.

– Overloaded operator functions can be invoked by


expressions such as:
Overloading binary operators
• Requires 2 operands to perform
• To add two numbers we are using arithmetic
notation than functional notation
• C=sum(A,B); //Functional notation
• C=A+B; //Arithmetic notation
• As a rule, in overloading binary operators,
– the left-hand operand is used to invoke the
operator function and
– the right-hand operand is passed as an argument.
#include<iostream.h> void display()
#include<conio.h> {
class complex cout<<a<<"+"<<b<<"i"<<"\n";
{ }
int a,b; };
public: void main()
void getvalue() {
{ clrscr();
cout<<"Enter the value of Complex complex obj1,obj2,result,result1;
Numbers a,b:";
cin>>a>>b; obj1.getvalue();
} obj2.getvalue();
complex operator+(complex ob)
{ result = obj1+obj2;
complex t; result1=obj1-obj2;
t.a=a+ob.a;
t.b=b+ob.b; cout<<"Input Values:\n";
return(t); obj1.display();
} obj2.display();
complex operator-(complex ob)
{ cout<<"Result:";
complex t; result.display();
t.a=a-ob.a; result1.display();
t.b=b-ob.b;
return(t); getch();
• Output:
Enter the value of Complex Numbers a, b
4 5
Enter the value of Complex Numbers a, b
2 2
Input Values
4 + 5i
2 + 2i
Result
6 + 7i
2 + 3i

• result=obj1+obj2; is same as
• result=obj1.opeartor+(obj2);
• Data members of obj2 are accessed by using dot operator
Rules for operator overloading
1. Only existing operators can be overloaded. New
operators cannot be created.
2. The overloaded operator must have at least one
operand that is of user-defined type.
3. We cannot change the basic meaning of an operator.
4. Overloaded operators follow the syntax rules of the
original operators.
Rules for operator overloading
5. The following operators that cannot be overloaded:
• Size of Size of operator
• . Membership operator
• .* Pointer-to-member operator
• :: Scope resolution operator
• ?; Conditional operator
Function Overriding
class Electronix {
public:
void show(int x) {
cout<<"\nThis is: "<<x;
}
};
class Computer: public Electronix {
public:
void show(int x) {
cout<<"\nThis is: "<<x*x;
}
};
void main( ) {
Computer c; c.show(5); Electronix e; e.show(6);
c. Electronix::show(4);
}
Run time polymorphism
• Same message respond in different forms
• We use pointer to base class to refer to all derived
objects.
• We use run time polymorphism when member
function name as well as arguments type is same
• When we use same function name in both base as
well as derived class, function in base class is
declared as virtual using keyword “virtual”
Virtual Function

class Base { void display( ) {


public: cout<<"\nDerived
void show( ) { display";
cout<<"\nBase show"; }
} };
virtual void display( ) void main()
{
{
Base b, *p;
cout<<"\nBase display";
Derived d;
}
p = &b; // statement 1
};
p -> show();
class Derived: public Base{
p -> display();
public:
p = &d; // statement 2
void show( ) {
p -> show();
cout<<"\nDerived show";
p -> display();
} }
Output:
class Engineering
{

protected: float result;


public:
virtual void show ( ) { }
};
class Mechanical: public Engineering
{
public: Mechanical(float x) {
result = x;
}
void show ( ) {
cout<<"\nMechanical Result: "<<result;
}

};
class Production: public Engineering {
public: Production(float y) {
result = y;
}
void show ( )
{

cout<<"\nProduction Result: "<<result;


}

};
void main( )
{

Engineering *ptr[2];
Mechanical m(87.63);
Production p(71.92);
ptr[0] = &m;// statement 1
ptr[0]-> show ( );
ptr[1]= &p; // statement 2
ptr[1]-> show();
getch();
}
Rules for virtual functions
1.Virtual function must be member of some class.
2.They can not be static members.
3.They are accessed by using object pointers.
4.A virtual function can be friend of another class.
5.A virtual function in the base class must be
defined, even though it may not be used.
6.In order to take advantage of virtual they must be
overridden functions.
7.We can't have virtual constructors but can
have virtual destructors.
8.We can not use pointer of the derived class to
access any thing from the base class.
9. If a virtual function is defined in the base
class, it need not be necessarily redefined in
the derived class. In such cases the base
function will be called.
Pure Virtual Function
• Definition: Pure virtual function is a virtual
function which has no body.
• Declaration: notation 0 indicates that virtual
function is pure virtual function
• Syntax:
Class classname
{
public:
Virtual void virtualfunctionname()=0;
};
Pure Virtual Function

class Base { void show( ) {


public: cout<<"\nDerived2 show";
virtual void show( ) =0; }
}; };
class Derived1: public Base{ void main()
{
public:
void show( ) { Base *p;
cout<<"\nDerived1 show"; Derived1 d1;
} Derived2 d2;
}; p = &d1; // statement 1
class Derived2: public Base{ p -> show();
public: p = &d2; // statement 2
p -> show();
getch();
}

You might also like