Pointer and Polymorphism in C++

Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

Pointer and polymorphism in c++

 Concepts of pointer:
Pointer-A pointer variable that holds the address of another pointer
variable is called pointer.
Or
Data type which holds the address of other data types.

 Pointer Declaration Syntax


The declaration of C++ takes the following syntax:
datatype *variable_name;

 The datatype is the base type of the pointer which must be


a valid C++ data type.
 The variable_name is should be the name of the pointer
variable.
 Asterisk used above for pointer declaration is similar to
asterisk used to perform multiplication operation. It is the
asterisk that marks the variable as a pointer.

Here is an example of valid pointer declarations in C++:


int *x; // a pointer to integer
double *x; // a pointer to double
float *x; // a pointer to float
char *ch // a pointer to a character

 There are mainly two types of Pointer operators


mainly used:-

 1) Address of operator (&)

 2)The indirection operator/Dereference operator(*)


Image showing the relation between pointer and variable

Reference operator (Address of &) and Deference operator


( value of *)
The reference operator (&) returns the variable’s address.

The dereference operator (*) helps us get the value that has
been stored in a memory address.

Or

The Address-of operator (&) is a unary operator that returns


the memory address of its operand which means it stores
the address of the variable, which depicts that we are only
storing the address not the numerical value of the operand. It
is spelled as the address of the variable.

The indirection/ dereference operator is a unary operator that


returns the value of the variable present at the given address.
It is completely opposite to the address-of operator. It is
spelled as a value pointed at the address.

For example:

If we have a variable given the name num, stored in the


address 0x234 and storing the value 28.
The reference operator (&) will return 0x234.

The dereference operator (*) will return 5.

Example :
#include <iostream>
using namespace std;
int main()
{
int x = 27;
int *ip;
ip = &x;
cout << "Value of x is : ";
cout << x << endl;
cout << "Value of ip is : ";
cout << ip<< endl;
cout << "Value of *ip is : ";
cout << *ip << endl;
return 0;
}

 Pointer Arithmetic-
Pointer arithmetic means performing arithmetic operations on
pointers. It refers to the operations that are valid to perform on
pointers.
Following are the arithmetic operations valid on pointers
in C++:
1. Incrementing and Decrementing Pointers.
2. Addition of Constant to Pointers.
3. Subtraction of Constant from Pointers.
4. Subtraction of Two Pointers of the Same Type.
5. Comparison of Pointers.

Example-
Pointer increment-
Int main()
{
Int a=10;
Int *ptr=&a;
Cout<<ptr;
Ptr++;
Cout<<ptr;
}

 Pointer to objects-
A pointer to an object acts the same as Pointer to a
variable. But here, in place of the address of the variable,
address of the object is stored. In the main function, when an
object is created to a class, a pointer variable is declared in the
same manner as we declared for the variable, and it will store
the object's address. For creating a pointer to an object, we
should not use data type for the Pointer. Instead, we need
to use the class name for the object pointer. If we want to
use a member function in the class using the Pointer in the
main function, then we need to use the -> symbol,
as shown in the below example.
Example:
using namespace std;
class Rectangle
{
private:
int length;
int breadth;
public:
Rectangle(int l, int b)
{
length=l;
breadth=b;
}
int getArea()
{
return 2*length*breadth;
}
};

int main()
// creating an object of
Rectangle
Rectangle var1(10,30);
//creating a pointer for the object
using class name as data type
Rectangle* ptr = &var1;
//calling the member
function using -> symbol
int area = ptr->getArea();
cout<<"Area of rectangle is: "<<area;
return 0;
}

 This pointer-

In C++ programming, this is a keyword that refers to the current


instance of the class.

This is a local object pointer in every instance member function


containing address of the caller object.
This pointer can not be modify.

It is used to refer caller object in member function ,when local


variables name is same as member’s name.

o It can be used to pass current object as a parameter to


another method.
o It can be used to refer current class instance variable.

Example-

Class test
{ private: int a;
Public:
void set_a(int a)
{ this->a=a; }
Void print_a()
{ cout<<”a=”<<a;
}
};
Int main()
{ text xobj;
Int a=5;
Xobj.set_a(a);
Xobj.print_a();
}
 Pointer to derived class
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 a pointer to the derived type.

A derived class is a class that takes some properties from its


base class. A pointer of one class can indeed point to another
class, but classes must be a base and derived class, then it is
possible.

Variable of the base class can be accessed through a base


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

In this pointer base class is owned by the base class but points
to the derived class object. Similarly, it works with derived class
pointer, values are changed.

Example #1

#include<iostream.h>

class base

public:

int n1;

void show()

{
cout<<”\nn1 = “<<n1;

};

class derive: public base

public:

int n2;

void show()

cout<<”\nn1 = “<<n1;

cout<<”\nn2 = “<<n2;

};

int main()

base b;
base *bptr; //base pointer

cout<<”Pointer of base class points to it”;

bptr=&b; //address of base class

bptr->n1=23; //access base class via base pointer

bptr->show();

derive d;

cout<<”\n”;

bptr=&d; //address of derive class

bptr->n1=63; //access derive class via base pointer

bptr->show();

return 0;

Output:

The pointer of the base class points to it

n1 = 23

The pointer of base class points to derive a class

n1=63
 Introduction to polymorphism: -

Polymorphism is an important concept of object-oriented


programming. It simply means more than one form. That is, the
same entity (function or operator) behaves differently in
different scenarios.

For example,

The + operator in C++ is used to perform two specific functions.


When it is used with numbers (integers and floating-point
numbers), it performs addition.
int a = 5;
int b = 6;
int sum = a + b; // sum = 11

And when we use the + operator with strings, it performs string


concatenation. For example,
string firstName = "abc ";
string lastName = "xyz";

// name = "abc xyz"


string name = firstName + lastName;

 Types of Polymorphism
 Compile-time Polymorphism
 Runtime Polymorphism
 function overloading –
Two functions having the same name if they have different
parameters .(either types or number of arguments).
OR
class Test
{
public:
// Function with
1 int parameter
void func(int x)
{
cout << "value of x is " << x << endl;
}

// Function with same name but 1


double parameter
void func(double x)
{
cout << "value of x is " << x << endl;
}

// Function with same name and 2


int parameters
void func(int x, int y)
{
cout << "value of x and y is " << x << ",
" << y
<< endl;
}
};

// Driver code
int main()
{
test obj1;
// Function being called depends on the
parameters passed func() is called with int value
obj1.func(7);

// func() is called
with double value
obj1.func(9.132);

// func() is called
with 2 int values
obj1.func(85, 64);

 Operator Overloading

Operator overloading is a compile-time polymorphism. It is an idea


of giving special meaning to an existing operator in C++ without
changing its original meaning.
Or

Operator overloading is a compile-time polymorphism in which


the operator is overloaded to provide the special meaning to
the user-defined data type. Operator overloading is used to
overload or redefines most of the operators available in C++. It
is used to perform the operation on the user-defined data type.
For example, C++ provides the ability to add the variables of
the user-defined data type that is applied to the built-in data
types.

 Difference between Operator Functions and Normal


Functions
Operator functions are the same as normal functions. The only
differences are, that the name of an operator function is always
the operator keyword followed by the symbol of the operator, and
operator functions are called when the corresponding operator is
used.

Operator that cannot be overloaded are as follows:

o Scope operator (::)


o Sizeof
o member selector(.)
o member pointer selector(*)
o ternary operator(?:)

Syntax of Operator Overloading

1. return_type operator op(argument_list)


2. {
3. // body of the function.
4. }
Where the return type is the type of value returned by the
function.

operator op is an operator function where op is the


operator being overloaded, and the operator is the
keyword.

There are some rules for the operator overloading.


These rules are like below

 Only built-in operators can be overloaded. If some operators


are not present in C++, we cannot overload them.
 The arity of the operators cannot be changed
 The precedence of the operators remains same.
 The overloaded operator cannot hold the default parameters
except function call operator “()”.
 We cannot overload operators for built-in data types. At least
one user defined data types must be there.
 The assignment “=”, subscript “[]”, function call “()” and arrow
operator “->” these operators must be defined as member
functions, not the friend functions.
 Some operators like assignment “=”, address “&” and comma
“,” are by default overloaded.

 overloading of unary & Binary operator


Unary Operator Overloading

As the name suggests, Unary operators operate on single


operand or data.
Following are the examples of Unary operators:

 Unary minus ( – ) operator


 Logical not ( ! ) operator
 Decrement ( — ) and Increment ( ++ ) operator

Note : If increment/decrement operators are used before


variable, they are called prefix operators i.e ++x. And
if increment/decrement operators are used after variable, they
are called postfix operators i.e x++.

Example: C++ program to illustrate the use of unary


operator overloading, increment ++ and decrement -
- operator overloading

Class demo
{ int x;
Public: void getdata()
{ cout<<”enter n:”;
Cin>>x;
}
Void putdata()
{ cout<<x;}
Void operator++()
{ x=x+1; }
};
int main()
{ demo aa;
aa.getdata();
cout<<”original value=”;
aa.putdata();
++aa;
Cout<<”value after increment=”;
aa.putdata();
}

Binary Operator Overloading

As the name suggests, those operators which operate on two


operands or data are called binary operators.

Here is an example to show how binary operators are overloaded


in C++.

Example: C++ program to illustrate binary operator


overloading

Class demo
{ int x;
Public: void getdata()
{ cout<<”enter n:”;
Cin>>x;
}
Void putdata()
{ cout<<x;}
demo operator+(demo bb)
{ demo cc;
cc.a=a+bb.a;
return cc; }
};
int main()
{ demo aa,bb,cc;
aa.getdata();
bb.getdata();
cc=aa+bb;
aa.putdata();
bb.putdata();
cc.putdata();
}

 Run time polymorphism :-


runtime polymorphism, the compiler resolves the object at run time
and then it decides which function call should be associated with that
object. It is also known as dynamic or late binding polymorphism.
This type of polymorphism is executed through virtual functions and
function overriding. All the methods of runtime polymorphism get
invoked during the run time.
 virtual functions
Virtual functions are the member functions of the base class which are
overridden in a derived class. When you make a call to such a
function by using a pointer or reference to the base class, the virtual
function is called and the derived class’s version of the function gets
invoked.

Or

It is a member function which is declared within base class and is


redefined by derived class.
When you refer to a derived class object using a pointer or a reference
to base class ,you can call a virtual function for that object and
execute the derived class function.

Some Key Points About Virtual Functions(rules for virtual function )

 Virtual functions are only dynamic.(not static )


 They are declared within a base class by using the keyword
“virtual”
 These functions are called during run time
 Virtual functions are always declared with a base class and
overridden in a child class
 Virtual functions can exist in the absence of inheritance. In
that case, the base class version of the function will be called.

 pure virtual functions.

A pure virtual function in c++ is a virtual function for which we do


not have an implementation. We do not write any functionality in it.
Instead, we only declare this function. A pure virtual function does
not carry any definition related to its base class. A pure virtual
function is declared by assigning a zero (0) in its declaration. Any
class containing one or more pure virtual functions can not be used to
define any object. For this reason, these classes are known as abstract
classes. Classes derived from abstract classes need to implement the
pure virtual functions of these classes.

Syntax

The syntax of the pure virtual function is as follows:

virtual <function_type> <function_name>() = 0;


We need to write "virtual" to create a virtual function. After that, we
declare the type of function, and then the function's name is written.
Since it is a pure virtual function, we must end this function by
assigning the value '0' zero to the function.

Characteristics of Pure Virtual Function in C++

The following are the characteristics of a pure virtual function in c++:

 A pure virtual function does not do anything, which means it is


used to resemble the template, and the derived classes
implement the function.
 It is an empty function because it does not contain any definition
of the functionality of its base class in it.
 Derived class can call a member or pure virtual function in c++.
 The user in the derived class redefines a pure virtual function.
 Any class in c++ that contains a pure virtual function does not
allow the user to create the object of that class.

Example-

#include <iostream>

using namespace std;

// here is Abstract class

class Shape {

public: virtual float cal_Area() = 0; // cal_Area is a pure


virtual function

};

class Square: public Shape {

float a;

public:

Square(float l) {
a = l;

float cal_Area() {

return a * a; // returns area of square

};

class Circle: public Shape {

float r;

public:

Circle(float x) {

r = x;

float cal_Area() {

return 3.14 * r * r;

};

class Rectangle: public Shape {

float l;

float b;

public:
Rectangle(float x, float y) {

l = x;

b = y;

float cal_Area() {

return l * b; // returns the product of length and breadth

};

int main() // main function

Shape * shape;

Square s(3.4);

Rectangle r(5, 6);

Circle c(7.8);

shape = & s;

int a1 = shape -> cal_Area();

shape = & r;

int a2 = shape -> cal_Area();

shape = & c;

int a3 = shape -> cal_Area();


std::cout << "The area of square is: " << a1 << std::endl;

std::cout << "The area of rectangle is: " << a2 << std::endl;

std::cout << "The area of circle is: " << a3 << std::endl;

return 0;

 The following table demonstrates the difference between


runtime polymorphism and compile-time polymorphism:

Compile Time Polymorphism Run time Polymorphism

In Compile time Polymorphism, In Run time Polymorphism, the


the call is resolved by the call is not resolved by the
compiler. compiler.

It is also known as Static It is also known as Dynamic


binding, Early binding and binding, Late binding and
overloading as well. overriding as well.

Method overloading is the Method overriding is the


compile-time polymorphism runtime polymorphism having
where more than one methods the same method with same
share the same name with parameters or signature but
different parameters or signature associated withcompared,
and different return type. different classes.

It is achieved by function
It is achieved by virtual
overloading and operator
functions and pointers.
overloading.
Compile Time Polymorphism Run time Polymorphism

It provides slow execution as


It provides fast execution
compare to early binding
because the method that needs to
because the method that needs
be executed is known early at the
to be executed is known at the
compile time.
runtime.

Compile time polymorphism is Run time polymorphism is


less flexible as all things execute more flexible as all things
at compile time. execute at run time.

Inheritance is not involved. Inheritance is involved.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy