You are on page 1of 140

TSSM’s

Bhivarabai Sawant College of Engineering & Research,


Narhe, Pune

UNIT 2
Inheritance and Pointers

Prof. S. B. Karale
Syllabus- Unit II

 Inheritance- Base Class and derived Class, protected members, relationship

between base Class and derived Class, Constructor and destructor in Derived
Class, Overriding Member Functions, Class Hierarchies, Public and Private
Inheritance, Types of Inheritance, Ambiguity in Multiple Inheritance, Virtual Base
Class, Abstract class, Friend Class , Nested Class.
 Pointers: declaring and initializing pointers, indirection Operators, Memory

Management: new and delete, Pointers to Objects, this pointer, Pointers Vs


Arrays, accessing Arrays using pointers, Arrays of Pointers, Function pointers,
Pointers to Pointers, Pointers to Derived classes, Passing pointers to functions,
Return pointers from functions, Null pointer, void pointer.
Inheritance
Introduction

 Reusability is important feature of OOP.

The mechanism of deriving a new class from an old one is called


Inheritance

• The old class is referred as base class


• The new class is referred as derived class
NEED AND CONCEPT

• Reusability is another important feature of OOP


• Using the features(data and/or functions) of one class into
another class
• Mechanism of deriving a new class from an old one is called as
inheritance(or derivation)
• The old class is referred as Base(super) class and new class is
called as derived(Sub) class

5
Inheritance
 Inheritance is the process by which objects of one class acquire the

properties of objects of another class.

Bird

Flying Bird NonFlying Bird

Parrot Sparrow Penguin Kiwi


Inheritance
Syntax: class derived-class : visibility-mode base-class

Examples: class ABC : private XYZ


XYZ
{

class ABC : public XYZ


ABC
{

class ABC : protected XYZ

}
EXAMPLE
class ABC : private XYZ // private derivation
{
// members of ABC
};

class ABC : public XYZ // public derivation


{
// members of ABC
};

class ABC : XYZ // private derivation by default


{
// members of ABC
}; 8
PRIVATE AND PUBLIC DERIVATION

Private derivation
• Public members of base → private of derived
● So public members of base(now private of derived) can be accessed
by member functions of derived
● Private members are not inheritable

Public derivation
• public members of base → public of derived
● Private members are not inheritable
9
Types of inheritance

1. single Inheritance

2. Multiple Inheritance

3. Hierarchical Inheritance

4. Multilevel Inheritance

5. Hybrid Inheritance
Forms of inheritance
A

A A B B

B C C

a) Single Inheritance b) Multiple Inheritance c) Multilevel Inheritance

A A

B C
B C D
D

d) Hierarchical Inheritance e) Hybrid Inheritance


Types of Inheritance
1. Single inheritance : one class inherits properties of another class

2. Multilevel Inheritance: deriving a class from another derived class

3. Multiple Inheritance: deriving a class from several other base classes

4. Hierarchical inheritance : deriving multiple subclasses from single base class

5. Hybrid inheritance : combination of hierarchical and multiple inheritance


1. Single Inheritance
 one class inherits properties of another class

Base
Class

A
Derived
Class

B
class B
{
int a; Single Inheritance : public
public:
int b;
void get_ab();
void show_a();
}; class D
{
class D : public B private:
{ int c;
int c; public:
public: int b;
void display() void get_ab();
}; void show_a();
Void display();
}
class B void B :: show_a()
{ {
int a;
public: cout << a;
int b;
}
void get_ab();
void D :: display()
void show_a();
{
};
cout << “a :=” << show_a();
cout << “b := ” << b;
class D : public B
cout << “c :=” << c;
{
}
int c;
public:
int main()
void display()
{
};
D d;
d.get_ab();
void B :: get_ab() d.show_a();
{ d.display();
a = 5; b = 10; d.b=20;
}; d.display();
return 0;
}
Single Inheritance : private
class B
{
int a;
public:
int b;
void get_ab(); class D
void show_a(); {
private:
};
int c;
class D : private B int b;
{ void get_ab();
int c; void show_a();
public: Public:
Void display();
void display()
}
};
void B :: get_ab()
{
a = 5; b = 10;
class B };
{ void B :: show_a()
{
int a;
cout << a;
public: }
int b; void D :: display()
void get_ab(); {
cout << “a :=” << show_a();
void show_a();
cout << “b := ” << b;
}; cout << “c :=” << c;
class D : private B }
{ int main()
{
int c;
D d;
public: d.get_ab(); // won’t work
void display() d.show_a(); // won’t work
d.display();
};
d.b=20; // won’t work
d.display();
return 0;
}
EFFECT OF INHERITANCE ON VISIBILITY OF MEMBERS
Not inheritable private Class B
Not inheritable
protected

public

Class D1 : public B
Not inheritableprivate Class D2 : private B private
Not inheritable

protected protected

public public

Class X : public D1 : protected D2 private

protected
18

public
Access rights of Derived Class

Type of Inheritance
Private Protected public
Private - - -
Access Control Protected Private Protected Protected
for Members
Public Private Protected public
2. Multilevel Inheritance
 deriving a class from another derived class

C
Multilevel Inheritance
class student
{
protected:
int roll_num;
public:
class test
void get_num(int);
{
void put_num();
protected:
};
int roll_num;
float sub1,sub2;
class test : public student
public:
{
void get_num(int);
protected:
void put_num();
float sub1, sub2;
void get_marks(float,float);
public:
void put_marks();
void get_marks(float,float);
}
void put_marks();
};
Multilevel Inheritance
class student class result : public test
{ {
protected: float total;
int roll_num; public :
public: void display();
void get_num(int); }
void put_num();
}; int main()
{
class test : public student result res;
{ res.get_num(111);
protected: res.get_marks(75.0, 69);
float sub1, sub2; res.display();
public: return 0;
void get_marks(float,float); }
void put_marks();
};
Multilevel Inheritance

Class result
{
private:
float total;
protected:
int roll_num;
float sub1,sub2;
public:
void get_num(int);
void put_num();
void get_marks(float,float);
void put_marks();
void display();
}
3. Multiple Inheritance
 deriving a class from several other base classes

A B

C
Multiple Inheritance
class M
{
protected:
int m;
public:
class P
void get_m(int);
{
};
protected:
class N
int m;
{
int n;
protected:
public:
int n;
void get_m(int);
public:
void get_n(int);
void get_n(int);
void display();
};
}
class P : public M, public N
{
public:
void display();
}
Multiple Inheritance
void M :: get_m(int x)
class M
{
{
m = x;
protected:
}
int m;
void N :: get_n(int y)
public:
{
void get_m(int);
n = y;
};
}
class N
void P :: display()
{
{
protected:
cout << m <<“ and”<< n;
int n;
}
public:
int main()
void get_n(int);
{
};
P p;
class P : public M, public N
p.get_m(10);
{
p.get_n(20);
public:
p.display();
void display();
return 0;
}
}
Ambiguity resolution in inheritance
 Same function name appears in more than base class.

class A class C:public A, public B


{ {
public:
void show() };
{
cout<<"A"; int main()
} {
}; C c;
c.show(); //Ambiguous call:
class B }
{
public:
void show()
{
cout<<"B";
}
};
Ambiguity in Multiple Inheritance
#include<iostream>
class A
• The members are ambiguous without scope
{ resolution operator when the member function
public:
Void show () show () is accessed by the derived class object,
{
naturally, the compiler can’t distinguish between
cout<<”\n class A”;
} member function of the class A and B.
};
class B
• The problem is resolved using scope-resolution
{ operator to specify the class in which the
public:
void show () function lies. Thus,
{
Obj.B:: show ();
cout<<”\n class B”;
} • Refers to the function in the B class. Thus,  the
};
class C: public A, public B
scope – resolution operator resolves the
{ ambiguity.
};
Void main()
{
C obj;
Obj. Show ();
}
Ambiguity resolution in inheritance
 Same function name appears in more than one base class.

class A class C:public A, public B


{ {
public:
void show() };
{
cout<<"A"; int main()
} {
}; C c;
c.A::show();
class B c.B::show();
{ //c.show();
public: }
void show()
{
cout<<"B";
}
};
4. Hierarchical Inheritance
 Deriving multiple subclasses from single base class

B C D
Hierarchical Inheritance (Example)
#include<iostream.h> class C :public A //Derived Class 2
class A //Base Class {
{ public:
public: void cube()
int a,b;
{
void getnumber()
getnumber();
{
cout<<"\n\tCube of the number ::\
cout<<"\n\nEnter Number :::\t";
t"<<(a*a*a);
cin>>a;
} }
}; };

class B : public A //Derived Class 1 int main()


{ {
public: B b1;
void square() b1.square();
{
getnumber(); cout<<"\nSquare of C c1;
the number::\t"<<(a*a);
c1.cube();
}
}
};
Output:
5. Hybrid Inheritance
• Combination of hierarchical and multiple inheritance

B C

D
class A {
public:
void Fun(){
}
};
A
class B : public A {
………
};
B C
class C : public A {
……….
};
D
class D : public B, public C {
………..
};
Virtual base class

B C

 The duplication of inherited members due to multiple paths can be avoided by

making the common base class as virtual base class.


Virtual base class
class A  int main() 
{  { 
     public:           D ob; 
          int i;           ob.i = 10; // only one copy of i is inherited. 
};          ob.j = 20; 
class B : virtual public A           ob.k = 30; 

       public:           ob.sum = ob.i + ob.j + ob.k; 
                int j;     
};       cout << “Value of i is : ”<< ob.i<<”\n”; 
class C: public virtual A           cout << “Value of j is : ”<< ob.j<<”\n”;
{  cout << “Value of k is :”<< ob.k<<”\n”; 
        public:        
             int k;     cout << “Sum is : ”<< ob.sum <<”\n”; 
};
return 0; 
class D: public B, public C  }.

public:  Output:
      int sum;  Value of i is :10
}; Value of j is : 20
Value of k is : 30
Sum is : 60
Virtual Function: Overriding Member Functions
#include<iostream> int main()
class base {
{   
    public:    base obj1;
      virtual void show()    base *p;
      {   
                cout<<"\n  Base class show:"; cout<<"\n\t P points to base:\n"  ;
      }  
      void display()    p=&obj1;
      {    p->display();
              cout<<"\n  Base class    p->show();
display:" ;  
      }    cout<<"\n\n\t P points to drive:\n";
};   
 class drive:public base drive obj2; Output:
{                  P points to Base
   public: p=&obj2;  
      void show()    p->display();
      {    p->show();            Base class display
              cout<<"\n  Drive class show:";                  Base class show
      } return 0;  
void display() }
      {
              P points to Drive
              cout<<"\n  Drive class display:";  
      }               Base class Display
};               Drive class Show
 
Virtual function
Class A  {  int main() 
int a;  { 
        public:             A *p;
        A(){
                 a = 1;  A a1; 
        }             B b1; 
        virtual void show()  {            
                    cout <<a; p = &a1;
        }  p->show(); 
};
Class B: public A  {  p = &b1; 
         int b;             p->show(); 
         public: 
          B() {       return 0; 
                 b = 2;  }
          }
         void show() {  
                  cout <<b; Output:
          }
}; 1
2
Constructors in derived class

 If base class have the constructor then it is mandatory to have

constructor in derived class.


 Base constructor is executed first then the derived class constructor.

 In Multilevel inheritance, constructor is executed in the order of

inheritance.
Rules for virtual function
 The virtual functions must be members 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 a base class must be defined, even though it may not

be used.
 We can not have a virtual constructor, but we can have virtual destructor.

 While a base pointer can points to any type of derived object, the reverse

is not true.
 If a virtual function is defined in the base class, it need not be necessarily

redefined in the derived class. In such a cases, calls will invoke the base
function.
Pure virtual function

 Compiler requires each derived class to either define the function or

redeclare as a pure virtual function.

Example:

class SomeClass {

public:

virtual void pure_virtual() = 0; // a pure virtual function

// note that there is no function body

};
Abstract Classes & Pure Virtual Functions
• Some classes exist logically but not physically.
• Example : Shape
– Shape s; // Legal but silly..!! : “Shapeless shape”
– Shape makes sense only as a base of some classes derived from it. Serves
as a “category”
– Hence instantiation of such a class must be prevented

class Shape //Abstract • A class with one or more pure


{ virtual functions is an Abstract
public : Class
//Pure virtual Function
• Objects of abstract class can’t be
virtual void draw() = 0;
created
}

Shape s; // error : variable of an abstract class


Abstract Class
class Shape /* Abstract class */
{ int main()
protected: {
float l; Square s;
public: void get_data() //not virtual Circle c;
{
cin>>l; cout<<"Enter length to calculate
} area of a square: ";
virtual float area() = 0;
}; //Pure virtual function s.get_data();

class Square : public Shape cout<<"Area of square: "<<s.area();


{
public: float area() cout<<"\nEnter radius to calcuate
{ area of a circle:";
return l*l;
} c.get_data();
}; cout<<"Area of circle: "<<c.area();
class Circle : public Shape
{ return 0;
public: float area() { return 3.14*l*l; } }
};
In this program, pure virtual function virtual float area() = 0; is defined inside
class Shape, so this class is an abstract class and you cannot create object of
Pointers to Derived Classes
 A pointer declared as a pointer to base class can also be used to point

to any class derived from that base.

 However, only those members of the derived object that were inherited

from the base can be accessed.


class BC int main()
{ {
public : BC *bptr;
int b; BC base;
void show() bptr=&base;
{ bptr->b=100;
cout<<"\n\n b="<<b; bptr->show(); Output:
} b=100
}; DC derived;
bptr=&derived;
class DC : public BC bptr->b=200; b=200
{ bptr->show();
public:
int d; DC *dptr;
b=200
void show() dptr=&derived; d=300
{ dptr->d=300;
cout<<"\n\nb="<<b; dptr->show();
cout<<“\nd="<<d;
b=200
} ((DC*)bptr)->d=400; d=400
}; ((DC*)bptr)->show();
return 0;
}
Friend Classes
It is possible for one class to be a friend of another class. When this is the
case, the friend class and all of its member functions have access to the
private members defined within the other class.
#include <iostream> class Min
using namespace std; {
public:
class TwoValues int minimum(TwoValues x);
{ };
int a;
int b; int Min::minimum (TwoValues x)
{
public: return x.a < x.b ? x.a : x.b;
TwoValues(int i, int j) }
{ int main()
a = i; {
b = j; TwoValues ob(10, 20);
} Min m;
cout << m.minimum(ob);
friend class Min; return 0;
}; }
Classes Within Classes
Local Classes

 A class defined within a function is called Local Class.

void fun()
Syntax: {
void function() class myclass {
{ int i;
class class_name public:
{ void put_i(int n) { i=n; }
// class definition int get_i() { return i; }
} obj; } ob;
//function body ob.put_i(10);
} cout << ob.get_i();
}
Multiple Classes

Synatax: Example: Example:


class class_name1 class test class student
{ { int st_id;
{ public: test m;
//class definition int t[3]; public:
}; }; viod init_test()
{
class class_name2
m.t[0]=25;
{ m.t[1]=22;
//class definition m.t[2]=24;
}; }
};
Nested Classes

Synatax: Example:
class student
class outer_class { int st_id;
{ public:
class dob
//class definition { public:
int dd,mm,yy;
class inner_class }dt;
{ void read()
{
//class definition dt.dd=25;
}; dt.mm=2;
dt.yy=1988;}
}; };
Polymorphism

Polymorphism

Compile Time Polymorphism Run Time Polymorphism


(Early Binding) (Dynamic Binding)

Function Operator Virtual Functions


Overloading Overloading (Function Overriding)
Pointers
Contents

 Computer Memory

 Variable

 Address operator (&)

 Pointer Variable

 Dereferencing Operator *

70
 Computer memory consists of sequence of bytes arranged one after other.

mory 1001 1002 1003 1004 1005 …………..n


dress:

71
 Variable:

 An identification(name) given to a memory location termed as variable.

72
 Each variable has assigned a unique address.
 Variable data will be stored on a specified address.

emory address: 1020 n


1024 1028

… … 100 … …
a
Variable a’s value, i.e., 100, is
stored at memory location 1024
int a = 100;
73
Address operator (&)

 Variable address printed by &variable_name

 Here & used to get address of variable.

emory address: n
1020 1024 1028

… … 100 … …
a
int a = 100; //get the value,
cout << a; //prints 100
cout << &a; //get the memory address
//prints 1024

74
Memory address: 1020 1024 1032

… 88 100 … … …
a b

#include <iostream> Result is:


The address of a is: 1020
using namespace std;
The address of b is: 1024
void main(){
int a, b;
a = 88;
b = 100;
cout << "The address of a is: " << &a << endl;
cout << "The address of b is: " << &b << endl;
}

75
 Pointer Variable:

 It is a variable used to store the address of another variable.

Memory address: 1020 1024 1032

… … 100 … 1024 …
integer
76 pointer
 Declaration pointer variable:

type* pointer_name;

//or

type *pointer_name;

 where type is the type of data pointed to (e.g. int, char, double, user defined

type)

77
Examples:
int *n;
ABC *r;
int **p; // pointer to pointer

78
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;

 The value of pointer p is the address of variable a


 A pointer is also a variable, so it has its own memory address
79
Dereferencing Operator *

 We can access to the value stored in the variable pointed to by using the

dereferencing operator (*),

Memory address: 1020 1024 1032

… 88 100 … 1024 …
int a = 100; a p Result is:
int *p = &a; 100
cout << a << endl; 1024
cout << &a << endl; 1024 100
cout << p << " " << *p << endl; 1032
cout << &p << endl;
80
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
cout << a << b << c

Output:
888

81
Pointer with function

void doubleIt(int x, int * p)


main
{

*p = 2 * x; p
a 8192
} 16 (8200)

int main() doubleIt


{ x 9
(8196)
int a = 16;

doubleIt(9, &a); doubleIt


a 16 main
cout<<a;
9 (8192)
x
return 0;

}
82 p a gets 18
#include <iostream>
using namespace std;
int main ()
{
int value1 = 5, value2 = 15;
int *p1, *p2; Let’s figure out:
p1 = &value1; // p1 = address of value1 value1==10 / value2==20
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;
}

83
Memory Management
 Memory Allocation in C++

 Static memory allocation

 Automatic memory allocation

 Dynamic memory allocation

85
 Memory Allocation in C++

 Static memory allocation

 This is a memory allocation done for static and global variables.

 Memory for these types of variables is allocated once when your

program is run and persists throughout the life of your program

86
 Memory Allocation in C++

 Automatic memory allocation( It is with block )

 The memory allocation is done for function parameters and local variables.

 Automatic memory management is closely related to local variables.

 A local variable occupies memory that the system allocates when it sees

the variable's definition during execution.


 The system also deallocates that memory automatically at the end of the

block that contains the definition.


 Memory for these types of variables is allocated when the relevant block is

entered, and freed when the block is exited, as many times as necessary.

87
 Memory Allocation in C++

 Dynamic memory allocation:

 The memory allocated at run time termed as dynamic memory allocation.

 The allocation can be done with

 malloc(), int * ptr = (int*) malloc(10 * sizeof(int));


 calloc(), int * ptr = (int*) calloc(1, sizeof(int));
 realloc() void *realloc(void *ptr, size_t size);

 new int *p;


p = new int;

88
 new
 C++ uses keyword called as new to allocate memory to type also
constructs object.

 Syntax

new data-type;

90
 data-type could be any built-in data type

 including an array

 user defined data types include class or structure.

91
 Heap memory deallocation.

 The memory allocated to data_type on heap can be deleted by

syntax

delete data_type

92
Example
Dynamic Memory Allocation

 Request for “unnamed” memory from the Operating System

new
 int *p, n=10;
p = new int; p

new

p = new int[100]; p
new
p = new int[n]; p
93
Freeing (or deleting) Memory

94
Memory Allocation Example
Want an array of unknown size #include <iostream>
using namespace std;
void main()
{
int n;
cout << “How many students? “;
cin >> n;
int *grades = new int[n];
for(int i=0; i < n; i++){
int mark;
cout << “Input Grade for Student” << (i+1) << “ ? :”;
cin >> mark;
grades[i] = mark;
}
...
printMean( grades, n ); // call a function with dynamic array
95 ...
}
 Dynamic Memory Allocation for Arrays:

char* pvalue = NULL; // Pointer initialized with null

pvalue = new char[20]; // Request memory for the variable

delete pvalue[]; //release memory

96
 Dynamic Memory Allocation for Objects:

 Objects are no different from simple data types.

97
using namespace std;
class Box
{
public:
Box() {
cout << "Constructor called!" <<endl;
}
~Box() {
cout << "Destructor called!" <<endl;
}
void show() {
cout<<“hellow world”;
}
};
int main( )
{
Box* myBoxArray = new Box[4];
myBoxArray[0].show();
delete [] myBoxArray; // Delete array
98 return 0;
}
Dynamic memory allocation for object

 The dynamic memory to an object is created by using -> operator.

 Ex

 Box *mybx=new Box();

 mybx->show();

99
Pointers to Objects

 A variable that holds an address value is called  a pointer variable or simply

pointer.
 Pointer can point to objects as well as to simple data types and arrays.

 sometimes we dont know, at the time that we write the program , how many

objects we want to create. when this is the case we can use new to


create objects while the program is running. new returns a pointer to an
unnamed objects.
void get()
#include <iostream>             {

#include <string>                         cout<<"enter roll no";

                        cin>>rollno;
using namespace std;
                        cout<<"enter  name";
class student                         cin>>name;

{ }

void print()
private:
            {
            int rollno;                         cout<<"roll no is "<<rollno;

            string name;                         cout<<"name is "<<name;

            }
public:
};
            student():rollno(0),name("") void main ()

            {} {

            student *ps=new student;


            student(int r, string n): rollno(r),name
            (*ps).get();
(n)             (*ps).print();

            {}             delete ps;

}
            
this pointer

 The this pointer holds the address of current object, in simple words you

can say that this pointer points to the current object of the class. Let’s take
an example to understand this concept.
void displayMyValues()
#include <iostream>
{
using namespace std;
cout<<num<<endl;
class Demo
cout<<ch;
{ private:
}
int num;
};
char ch;
int main()
public:
{
void setMyValues(int num, char ch)

{ Demo obj;

this->num =num; obj.setMyValues(100, 'A');  

this->ch=ch; obj.displayMyValues();

} return 0;

}
Pointer vsArray
 Array:

 It is a collection of similar data type.

105
 Defining Arrays

type array_name[size];
 Example

int test[85];

106
 Array Elements

 The maximum number of elements an array can hold depends upon the

size of an array.

107
int age[5];
 This is array with name age holding 5 integer values.

1001 1005 1009 1013 1017


108
 Array Initialization

int test[5] = {12, 3, 4, -3, 9};


int test[ ] = {12, 3, 4, -3, 9};

109
 Retrieving array value

 The value can be retrieved as

 array_name[index]

10 20 30 40 50

1001 1005 1009 1013 1017


Cout<<age[0];

110
Pointers and Array
 While handling arrays with pointers you need to take care few things.

First and very important point to note regarding arrays is that the array
name alone represents the base address of array so while assigning the
address of array to pointer don’t use ampersand sign(&). Do it like this:

Correct: Because arr represent the address of array.

p = arr;

Incorrect:

p = &arr;
 Example: Traversing the array using Pointers

#include <iostream>
using namespace std;
int main()
{
int *p; //Pointer declaration
int arr[]={1, 2, 3, 4, 5, 6}; //Array declaration
p = arr; //Assignment
for(int i=0; i<6;i++)
{  
cout<<*p<<endl;
p++;     //++ moves the pointer to next int position
}
return 0;
}
Output:
 123456
 How to increment pointer address and pointer’s value?
 When we are accessing the value of a variable through pointer,
sometimes we just need to increment or decrement the value of
variable though it or we may need to move the pointer to next int
position(just like we did above while working with arrays).
 // Pointer moves to the next int position (as if it was an array)

p++;
// Pointer moves to the next int position (as if it was an array)
++p;
/* All the following three cases are same they increment the
value * of variable that the pointer p points. */
++*p;
++(*p);
++*(p);
 The name of an array points only to the first element not the
whole array.

1000

1004

1008

1012

1016

115
Array Name is a pointer constant
#include <iostream>
using namespace std;

void main ()
{
int a[5];
cout << "Address of a[0]: " << &a[0] << endl
<< "Name as pointer: " << a << endl;
}

Result:
Address of a[0]: 0x0065FDE4
Name as pointer: 0x0065FDE4

116
Dereferencing An Array Name

This element is
called a[0] or
*a

#include <iostream>
a[0] 2 using namespace std;
a int main(){
a[1] 4 int a[5] = {2,4,6,8,22};
a[2] cout << *a << " “ << a[0];
6 return 0;
a[3] } //main
8
a[4] 22 Output:
2 2

117
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};
a[1] 4 int *p = a;
6 cout << a[0] << " “ << *p;
a[2] }
a[3] 8
22 Output:
a[4] 2 2
118
Multiple Array Pointers

 Both a and p are pointers to the same array.

a[0]
#include <iostream>
a[0] 22
2 using namespace std;
44
void main(){
a[1] 4 p int a[5] = {2,4,6,8,22};
a[2] 6 int *p = &a[1];
cout << a[0]<< " “<< p[-1];
a[3] 8 p[0] cout << a[1] << " “ << p[0];
a[4] }
22

119
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
120
NULL pointer

 NULL is a special value that indicates an empty pointer

 If you try to access a NULL pointer, you will get an error

int *p;

p = 0;

cout << p << endl; //prints 0

cout << &p << endl;//prints address of p

cout << *p << endl;//Error!

121
Function Pointer
Function Pointer
 unlike normal data pointers (int *, char *, etc), we can have pointers to

functions.
int main()
{
#include <iostream>

void fun(int a)
      void (*fun_ptr)(int) = &fun; 
    /* The above line is equivalent of
{ following two
    cout<<"Value of a is=“<< a;        
} void (*fun_ptr)(int);
 
 
      fun_ptr = &fun;     */
    
Output: // Invoking fun() using fun_ptr
Value of a is 10
    (*fun_ptr)(10);  
    
return 0;
123
}
Some interesting facts about function pointers.

 Unlike normal pointers, a function pointer points to code, not data.

 Typically a function pointer stores the start of executable code.

 Unlike normal pointers, we do not allocate de-allocate memory using function

pointers.

 A function’s name can also be used to get function’s address.

 For example, in the below program, we have removed address operator ‘&’

in assignment.
 We have also changed function call by removing *, the program still works.

124
Function Pointer
 unlike normal data pointers (int *, char *, etc), we can have pointers to

functions.
#include <iostream>

void fun(int a)
{
    cout<<"Value of a is=“<< a;
}
 
int main()
{

      void (*fun_ptr)(int) = fun;  


Output:
Value of a is 10        (fun_ptr)(10);  
    
return 0;
}
125
Function pointer with class

Syntax:

data-type (className::*pointerName)(parameters);

 Calling outside a class

object.*pointerName

126
#include<iostream>
using namespace std;
class ABC
{
public:  The *vptr1 is banded to
void fun() { cout<<"from fun"; } object of class.
};
int main() {
ABC *a;
a=new ABC();
void (ABC::*vptr1)();
vptr1=&ABC::fun;
(a->*vptr1)();
return 0;

127
}
Pointers to Pointers

 A pointer to a pointer is a form of multiple indirection or a chain of

pointers. Normally, a pointer contains the address of a variable.


 When we define a pointer to a pointer, the first pointer contains the

address of the second pointer, which points to the location that contains
the actual value as shown below.
 A variable that is a pointer to a pointer must be declared as such. This is

done by placing an additional asterisk in front of its name.


 For example, following is the declaration to declare a pointer to a

pointer of type int −

int **var;

 When a target value is indirectly pointed to by a pointer to a pointer,

accessing that value requires that the asterisk operator be applied twice
#include <iostream> // take the value using pptr

using namespace std; cout << "Value of var :" << var <<
endl;
int main ()
cout << "Value available at *ptr :"
{
<< *ptr << endl;
int var;
cout << "Value available at
int *ptr;
**pptr :" << **pptr << endl;
int **pptr;
return 0;
var = 3000;
}
// take the address of var

ptr = &var; Output:-


// take the address of ptr using address Value of var :3000
of operator &
Value available at *ptr :3000
pptr = &ptr;
Value available at **pptr :3000
Pointers to Derived classes

 Pointers to objects of a base class are type


compatible with pointers to objects of a derived class.
 A single pointer variable can be made to point to

objects belonging to different classes.


#include<iostream.h> int main()
class base {
{     base b;
     public:     base *bptr;      //base pointer
     int n1;     cout<<”Pointer of base class points to it”;
     void show()     bptr=&b;          //address of base class
     {     bptr->n1=44;     //access base class via base pointer
         cout<<”\n n1 = “<<n1;     bptr->show();
     }     derive d;
};     cout<<”\n”;
class derive : public base     bptr=&d;          //address of derive class
{     bptr->n1=66;        //access derive class via base pointer

     public:     bptr->show();

     int n2;     return 0;

     void show() }

     { Output :-
         cout<<”\n n1 = “<<n1; Pointer of base class points to it
         cout<<”\n n2 = “<<n2;           n1 = 44
     } Pointer of base class points to derive class
}; n1=66
Passing Pointers to Functions in C++

 C++ allows you to pass a pointer to a function. To do so, simply declare

the function parameter as a pointer type.


#include <iostream>
#include <ctime>
using namespace std;
void getSeconds(unsigned long *par);
int main ()
{
unsigned long sec;
getSeconds( &sec );
// print the actual value
cout << "Number of seconds :" << sec << endl;
return 0;
}
void getSeconds(unsigned long *par)
{ // get the current number of seconds
*par = time( NULL );
return;
}
#include <iostream>
using namespace std;
// function declaration:
double getAverage(int *arr, int size);
int main ()
{
// an int array with 5 elements.
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
// pass pointer to the array as an argument.
avg = getAverage( balance, 5 ) ;
// output the returned value
cout << "Average value is: " << avg << endl;
return 0;
}
double getAverage(int *arr, int size)
{
int i, sum = 0;
double avg;
for (i = 0; i < size; ++i)
{ sum += arr[i]; }
avg = double(sum) / size;
return avg;
}
Return Pointer from Functions in C++
 C++ allows to return an array from a function, similar way C++ allows you to

return a pointer from a function. 


 To do so, you would have to declare a function returning a pointer as in the

following example −
int * myFunction()
{
.
.
.
}
 Second point to remember is that, it is not good idea to return the address of a
local variable to outside of the function, so you would have to define the local
variable as static variable.
#include <iostream>
#include <ctime>
using namespace std;
// function to generate and retrun random numbers.
int * getRandom()
{
static int r[10];
// set the seed
srand( (unsigned)time( NULL ) );
for (int i = 0; i < 10; ++i)
{
r[i] = rand();
cout << r[i] << endl;
}
return r;
}
// main function to call above defined function.
int main ()
{
// a pointer to an int.
int *p;
p = getRandom();
for ( int i = 0; i < 10; i++ )
{
cout << "*(p + " << i << ") : ";
cout << *(p + i) << endl;
}
return 0;
}
NULL pointer
 NULL is a special value that indicates an empty pointer

 If you try to access a NULL pointer, you will get an error

 It is always a good practice to assign the pointer NULL to a pointer variable in case

you do not have exact address to be assigned.


 This is done at the time of variable declaration.

 A pointer that is assigned NULL is called a null pointer.

 The NULL pointer is a constant with a value of zero defined in several standard

libraries, including iostream.

int *p;

p = 0;

cout << p << endl; //prints 0

cout << &p << endl;//prints address of p

cout << *p << endl;//Error!


#include <iostream>
using namespace std;
int main ()
{
int *ptr = NULL;
cout << "The value of ptr is " << ptr ;
return 0;
}

 if(ptr) // succeeds if p is not null

 if(!ptr) // succeeds if p is null


Void pointer in C++

 A void pointer is a pointer that has no associated data type with it.

 A void pointer can hold address of any type and can be typcasted to any

type.

int a = 10;

char b = 'x';

void *p = &a;  // void pointer holds address of int 'a'

p = &b; // void pointer holds address of char 'b'


#include<stdio.h>
int main()
{
    int a = 10;
    void *ptr = &a;
    printf("%d", *(int *)ptr);
    return 0;
}

You might also like