0% found this document useful (0 votes)
5 views

UNIT-II_OOP_RBK

The document provides an overview of inheritance in C++, detailing its definition, types, and advantages. It explains various inheritance types such as single, multiple, multilevel, hierarchical, and hybrid inheritance, along with access specifiers and visibility modes. Additionally, it includes examples of class definitions and the behavior of constructors and destructors in derived classes.

Uploaded by

jay thorat
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)
5 views

UNIT-II_OOP_RBK

The document provides an overview of inheritance in C++, detailing its definition, types, and advantages. It explains various inheritance types such as single, multiple, multilevel, hierarchical, and hybrid inheritance, along with access specifiers and visibility modes. Additionally, it includes examples of class definitions and the behavior of constructors and destructors in derived classes.

Uploaded by

jay thorat
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/ 154

Unit –II

Inheritance & pointers


DEFINATION
Inheritance is a mechanism of creating new
classes called derived class from existing
ones i.e. base classes.
Inheritance is a most powerful feature of
object oriented programming.
C++ and inheritance
• The language mechanism by which one class
acquires the properties (data and operations)
of another class
• Base Class (or superclass): the class being
inherited from
• Derived Class (or subclass): the class that
inherits
Advantages of inheritance
• When a class inherits from another class,
there are three benefits:
• (1) You can reuse the methods and data of
the existing class
(2) You can extend the existing class by
adding new data and new methods
(3) You can modify the existing class by
overloading its methods with your own
implementations
Types of Inheritance
 Single Level Inheritance
 Multiple Inheritance
 Multilevel Inheritance
 Hierarchical Inheritance
 Hybrid Inheritance
SINGLE INHERITANCE
When a derived class inherits only from one
base class ,it is Known as single Inheritance.

A Base / super / parent Class

B
Derived / sub / child Class
MULTIPLE INHERITANCE
When a derived class inherit from multiple
base classes it is known as multiple
Inheritance.

A B Base Class

Derived Class
C
MULTILEVEL INHERITANCE
When a derived class inherit from a class that
itself inherits from other class , it is known as
multilevel Inheritance.
A
Base Class

Derived Class of A
B Base Class of C

Derived Class
C
HIERARCHICAL INHERITANCE
When many derived classes inherit from a
single base class , it is known as
hierarchical Inheritance.
A Base Class

B C D

Derived classes
HYBRID INHERITANCE
Hybrid Inheritance combines two or more forms
of Inheritance.
A

B C

D
DEFINING DERIVED CLASS
A general form to defining a derived class is:
Class derived_class_name : visibility_mode base_class_name
{
members of derived class
} ;

Example :

Class ABC: public XYZ


{
members of ABC
};
Example of derived class definition is:

Class Sub : public Super \\ public derivation


{
……… \\ members of sub
};

Class Sub: private Super \\ private derivation


{
……... \\ members of sub
};

Class Sub: protected Super \\ protected derivation


{
……... \\ members of sub
};
MULTIPLE INHERITANCE
Example of derived class definition is:

Class derived_class : vis_mode base1, vis_mode base 2


{
…………. \\ members of derived class
};

Class Sub : public SuperA, private SuperB


{
……… \\ members of sub
};
Class Hierarchies
• When several classes are derived from
common base class it is called hierarchical
inheritance.
• In C++ hierarchical inheritance, the feature of
the base class is inherited onto more than one
sub-class.
• For example, a car is a common class from
which Audi, Ferrari, Maruti etc can be derived.
Class Hierarchies

Class A

Class B Class C Class D


class A // base class
{ ..........public /protected.... };
class B : private A // derived class from A
{ ........... } ;
class C : access_specifier A // derived class from
A
{ ........... } ;
class D : access_specifier A // derived class from A
{ ........... } ;
3 Types of Access Specifiers

• Type 1: inherit as private


Base Derived

private members inaccessible

protected members private members

public members private members


3 Types of Access Specifiers
• Type 2: inherit as protected

Base Derived

private members inaccessible

protected members protected members

public members protected members


3 Types of Access Specifiers
• Type 3: inherit as public

Base Derived

private members inaccessible

protected members protected members

public members public members


Visibility Modes
DEFINATION:-
Visibility Mode specifies whether the features of the
base class are privately derived or publicly derived or
protected derived.

Public Visibility Mode- It means that the derived


class can access the public and protected members
of the base class. The public members of the base
class become the public member of the derived
class, and the protected member of the base class
become the protected member of the derived class.
Private Visibility Mode- The public and protected
members of the base class become private members of
the derived class. The inherited members can only be
accessed only through the member function of derived
class.

Protected Visibility Mode- The public and protected


members of base class become protected members of
the derived class.
Visibility of Inherited base class members in Derived
Class.

Visibility Public Protected Private


Mode members members members
of base of base of the
class class base class
becomes becomes is not
Public Public Protected accessible
to the
derived
Protected Protected Protected
class.

Private Private Private


Derived class visibility

Base Class
Visibility Public Private Protected
derivation derivation derivation

Private Not Not Not


inherited inherited inherited

Protected Protected Private Protected

Public Public Private Protected


Accessibility of Base class members
Access Accessible Accessible Accessible
Specifier from own from from objects
class derived outside class
class
Public Yes Yes Yes

Protected Yes Yes No

Private Yes No No
class MyClass { // The class
public: // Access specifier
// class members goes here
};

class MyClass {
int x; // Private attribute
int y; // Private attribute
};
PROGRAM: 1
#include <iostream>
using namespace std;

class MyClass {
public: // Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute
};

int main() {
MyClass myObj;
myObj.x = 25; // Allowed (x is public)
myObj.y = 50; // Not allowed (y is private)
return 0;
}

Output:
In function 'int main()':
Line 8: error: 'int MyClass::y' is private
Line 14: error: within this context
PROGRAM: 2 #include <iostream>
using namespace std;
// Parent class
class MyClass {
public:
void myFunction() {
cout << "Some content in parent class." ;
}
};
// Child class
class MyChild: public MyClass {
};
// Grandchild class
class MyGrandChild: public MyChild {
};
int main() {
MyGrandChild myObj;
myObj.myFunction();
return 0;
}

Output:

Some content in parent class.


PROGRAM: 3
#include <iostream>
using namespace std;

// Base class
class MyClass { int main() {
public: MyChildClass myObj;
void myFunction() { myObj.myFunction();
cout << "Some content in parent class.\n" ; myObj.myOtherFunction();
} return 0;
}; }

// Another base class Output:


class MyOtherClass {
public: Some content in parent class.
void myOtherFunction() { Some content in another class.
cout << "Some content in another class.\n" ;
}
};

// Derived class
class MyChildClass: public MyClass, public
MyOtherClass {
};
Constructors and Destructors in Derived
Classes
• Invocation of constructors and destructors
depends on the type of inheritance being
implemented. We have presented you the
sequence in which constructors and
destructors get called in single and multiple
inheritance.
• When we are using the constructors and
destructors in the inheritance, parent class
constructors and destructors are accessible to
the child class hence when we create an
object for the child class, constructors and
destructors of both parent and child class get
executed.
Constructors and Destructors in Derived
Classes
• Constructor and destructor in single
inheritance
• Base class constructors are called first and the
derived class constructors are called next in
single inheritance.
• Destructor is called in reverse sequence of
constructor invocation i.e. The destructor of
the derived class is called first and the
destructor of the base is called next.
Single Inheritance:
int main()
#include <iostream> {
using namespace std; derived ob;

class base { // do nothing but construct


public: and destruct ob
base() { cout << "Constructing base\n"; }
~base() { cout << "Destructing base\n"; } return 0;
}; }

class derived: public base { Output:


public: Constructing base
derived() { cout << "Constructing Constructing derived
derived\n"; } Destructing derived
~derived() { cout << "Destructing Destructing base
derived\n"; }
};
class derived2: public derived1 {
Hierarchical Inheritance: public:
derived2() { cout << "Constructing
#include <iostream> derived2\n"; }
using namespace std; ~derived2() { cout << "Destructing
class base derived2\n"; }
public: };
base() { cout << "Constructing base\ int main()
{
n"; } derived2 ob;
~base() { cout << "Destructing base\
n"; } // construct and destruct ob

return 0;
};
}
class derived1 : public base {
public: Output:
derived1() { cout << "Constructing Constructing base
derived1\n"; } Constructing derived1
Constructing derived2
~derived1() { cout << "Destructing Destructing derived2
derived1\n"; } Destructing derived1
}; Destructing base
Constructing base1 Constructing base2 Constructing derived Destructing derived Destructing base2 Destructing base1
Inheritance: Multiple base classes class derived: public base1, public
#include <iostream> base2 {
public:
using namespace std;
derived() { cout << "Constructing
class base1 { derived\n"; }
public: ~derived() { cout << "Destructing
base1() { cout << "Constructing derived\n"; }
base1\n"; } };
int main()
~base1() { cout << "Destructing
{
base1\n"; } derived ob;
}; // construct and destruct ob
return 0;
class base2 { }
Output:
public:
Constructing base1
base2() { cout << "Constructing Constructing base2
base2\n"; } Constructing derived
~base2() { cout << "Destructing Destructing derived
base2\n"; } Destructing base2
Destructing base1
};
Constructor and Destructor in Multiple
Inheritance

• Constructors from all base class are invoked


first and the derived class constructor is called.
• Order of constructor invocation depends on
the order of how the base is inherited
• E.g.
• class D:public B, public C
{
//…
}
• B is inherited first, so the constructor of class B is
called first and then constructor of class C is called
next.
• The destructor of derived class is called first and
then destructor of the base class which is
mentioned in the derived class declaration is called
from last towards first in sequentially.
/*C++ program to show the order of class Child : public Parent1, public Parent2
constructor calls in Multiple Inheritance*/ {
#include <iostream> public:
using namespace std;
class Parent1 // child class's Constructor
{ Child()
public: {
Parent1() cout << "Inside child class" << endl;
{
}
};
cout << "Inside first base class" <<
endl; // main function
int main() {
}
};
// creating object of class Child
class Parent2
Child obj1;
{
return 0;
public: }
Parent2() Output:
{
cout << "Inside second base class" Inside first base class
<< endl; Inside second base class
} Inside child class
};
// C++ program to show how to call parameterized Constructor
// of base class when derived class's Constructor is called
#include <iostream>
using namespace std;

class Parent
{
int x;
public:
// base class's parameterized constructor
Parent(int i)
{
x = i;
cout << "Inside base class's parameterized constructor" << endl;
}
};
// sub class
class Child : public Parent {
public:
// sub class's parameterized constructor
Child(int x): Parent(x)
{
cout << "Inside sub class's parameterized constructor"<< endl;
}
};
// main function
int main()
{
// creating object of class Child
Child obj1(10);
return
Output:0;
}
Inside base class's parameterized constructor
Inside sub class's parameterized constructor
C++ program:
#include<iostream> A2()
using namespace std; {
int x = 50, y = 42, z;
class A1
z = x - y;
{ cout << "Difference is:" <<
public: z << endl;
A1() }
{ };
int a = 20, b = 35, c; class S: public A1,virtual A2
{
c = a + b;
public:
cout << "Sum is:" << S(): A1(), A2()
c << endl; {
} int r = 40, s = 8, t;
}; t = r * s;
class A2 cout << "Product is:" <<
t << endl;
{
}
public: };
// Driver code
int main()
{
S obj;
return 0;
}
Output
Difference is:8
Sum is:55
Product is:320
C++ program to implement constructors
in multiple inheritance class D : public B, public C {
#include <iostream> };
using namespace std;
int main()
{
class A { D object;
public: object.show();
void show() }
{
cout << "Hello form A \n"; Output:
prog.cpp: In function 'int main()':
}
prog.cpp:29:9: error: request for
}; member 'show' is ambiguous
object.show();
class B : public A { ^
}; prog.cpp:8:8: note: candidates are:
void A::show()
void show()
class C : public A {
^
}; prog.cpp:8:8: note: void
A::show()
How to resolve this issue?
To resolve this ambiguity when class A is inherited in both class B and class
C, it is declared as virtual base class by placing a keyword virtual as :
Syntax for Virtual Base Classes:
Syntax 1:
class B : virtual public A
{
};
Syntax 2:
class C : public virtual A
{
};
virtual can be written before or after the public. Now only one copy of data,
function member will be copied to class C and class B and class A becomes
the virtual base class. Virtual base classes offer a way to save space and
avoid ambiguities in class hierarchies that use multiple inheritances. When a
base class is specified as a virtual base, it can act as an indirect base more
than once without duplication of its data members. A single copy of its data
members is shared by all the base classes that use virtual base.
C++ program: class D : public B, public C {
};
#include <iostream>
using namespace std; int main()
class A { {
D object; // object creation of class d
public:
cout << "a = " << object.a << endl;
int a;
A() // constructor return 0;
{ }
a = 10;
} Output
a = 10
};

class B : public virtual A {


};

class C : public virtual A {


};
C++ program: class D : public B, public C {
};
#include <iostream>
using namespace std; int main()
{
D object;
class A {
object.show();
public: }
void show()
{
cout << "Hello from A \n";
} Output
};
Hello from A

class B : public virtual A {


};

class C : public virtual A {


};
Overriding Member Functions
• Function overriding is a feature that allows us
to have a same function in child class which is
already present in the parent class.
• A child class inherits the data members and
member functions of parent class, but when
you want to override a functionality in the child
class then you can use function overriding.
• It is like creating a new version of an old
function, in the child class.
Access Overridden Function in C++

• To access the overridden function of the base


class, we use the scope resolution operator ::

• We can also access the overridden function by


using a pointer of the base class to point to an
object of the derived class and then calling the
function from that pointer
Difference between function overloading and function overriding

1) Function Overloading happens in the same class when


we declare same functions with different arguments in
the same class. Function Overriding is happens in the
child class when child class overrides parent class
function.

2) In function overloading function signature should be


different for all the overloaded functions. In function
overriding the signature of both the functions
(overriding function and overridden function) should
be same.
Difference between function overloading and function overriding

3) Overloading happens at the compile time that's


why it is also known as compile time
polymorphism while overriding happens at run
time which is why it is known as run time
polymorphism.

4) In function overloading we can have any number


of overloaded functions. In function overriding we
can have only one overriding function in the child
class.
Class A
{
Int area(int r)
{
//body
}
Float area (int l,int h)
{
//body
}
};
A a;
a.area(10);
a.area(12,11);
Class A
{
void print()
{
//body
}
};
Class B: public A
{
void print()
{
}
};
Ambiguity in multiple inheritance
• The most obvious problem with multiple
inheritance occurs during function overriding.
• Suppose, two base classes have a same
function which is not overridden in derived
class.
• If you try to call the function using the object
of the derived class, compiler shows error. It's
because compiler doesn't know which
function to call.
Virtual Base Class
• Virtual base classes are used in virtual
inheritance in a way of preventing multiple
“instances” of a given class appearing in an
inheritance hierarchy when using multiple
inheritances.
Need for Virtual Base Classes:
• Consider the situation where we have one
class A .This class is A is inherited by two other
classes B and C. Both these class are inherited
into another in a new class D as shown in
figure below.
• Data members/function of class A are
inherited twice to class D.
• One through class B and second through
class C.
• When any data / function member of class A is
accessed by an object of class D, ambiguity
arises as to which data/function member
would be called?
• One inherited through B or the other inherited
through C. This confuses compiler and it
displays error.
How to resolve this issue?
• To resolve this ambiguity when class A is inherited
in both class B and class C, it is declared as virtual
base class by placing a keyword virtual as :
• Syntax 1:
class B : virtual public A
{ };
Syntax 2:
class C : public virtual A
{};
• virtual can be written before or after the public.
• Now only one copy of data/function member will
be copied to class C and class B and
class A becomes the virtual base class.
• Virtual base classes offer a way to save space and
avoid ambiguities in class hierarchies that use
multiple inheritances.
• When a base class is specified as a virtual base, it
can act as an indirect base more than once
without duplication of its data members.
• A single copy of its data members is shared by all
the base classes that use virtual base.
Abstract Class
• Abstract Class is a class which contains at least
one Pure Virtual function in it.
• Abstract classes are used to provide an Interface
for its sub classes.
• Classes inheriting an Abstract Class must provide
definition to the pure virtual function, otherwise
they will also become abstract class.
Pure Virtual Functions

Pure virtual functions are used


• If a function doesn't have any use in the base
class but the function must be implemented
by all its derived classes
Pure Virtual Functions in C++

• Pure virtual Functions are virtual functions


with no definition. They start
with virtual keyword and ends with = 0.
• Here is the syntax for a pure virtual function,
• virtual void f() = 0;
Class Base
{
Public:
Virtual void show()=0;
};
Class Derived:public base
{
Public:
Void show()
{
//
}
Characteristics of Abstract Class

• Abstract class cannot be instantiated, but pointers


and references of Abstract class type can be
created.
• Abstract class can have normal functions and
variables along with a pure virtual function.
• Abstract classes are mainly used for Upcasting, so
that its derived classes can use its interface.
• Classes inheriting an Abstract Class must implement
all pure virtual functions, or else they will become
Abstract too.
// C++ Program to illustrate the abstract class and public:
virtual functions // implementation of the pure virtual
function
#include <iostream>
using namespace std; void fun() { cout << "fun() called"; }
};
class Base {
// private member variable int main(void)
int x; {
// creating an object of Derived class
public: Derived d;
// pure virtual function
virtual void fun() = 0; // calling the fun() function of Derived
class
// getter function to access x
int getX() { return x; } d.fun();
};
return 0;
// This class inherits from Base and implements fun() }
class Derived : public Base { Output:
// private member variable fun() called
int y;
// C++ program to calculate the area of a square public:
and a circle float calculateArea() {
#include <iostream> return 3.14 * dimension *
using namespace std; dimension;
// Abstract class }
class Shape { };
protected:
float dimension; int main() {
public: Square square;
void getDimension() { Circle circle;
cin >> dimension;
} cout << "Enter the length of the
// pure virtual Function square: ";
virtual float calculateArea() = 0; square.getDimension();
}; cout << "Area of square: " <<
// Derived class square.calculateArea() << endl;
class Square : public Shape {
public: cout << "\nEnter radius of the
float calculateArea() { circle: ";
return dimension * dimension; circle.getDimension();
} cout << "Area of circle: " <<
}; circle.calculateArea() << endl;
// Derived class return 0;
class Circle : public Shape { }
Output:
Enter the length of the square: 4
Area of square: 16

Enter radius of the circle: 3


Area of circle: 28.26
Friend Class
• As we know that a class cannot access the private
members of other class. Similarly a class that
doesn’t inherit another class cannot access its
protected members.
• A friend class is a class that can access the private
and protected members of a class in which it is
declared as friend. This is needed when we want
to allow a particular class to access the private
and protected members of a class.
Friend function program: main()
#include<iostream> {
using namespace std; A a;
B b;
class A b.display(a);
{ return 0;
int x; }
public:
A() Output:
{
x=10; The value of x=10
}
friend class B; //friend class In this example, class B is declared
}; as a friend inside the class A.
class B B is a friend of class A so, Class B
{ can access the private members of
public: class A.
void display(A &t)
{
cout<<endl<<"The value of x="<<t.x;
}
};
Nested Class
• A nested class is a class that is declared in
another class. The nested class is also a
member variable of the enclosing class and
has the same access rights as the other
members. However, the member functions of
the enclosing class have no special access to
the members of a nested class.
Nested Class
• Syntax:
Class A
{
//data members
//functions
Class B
{
//body
};
};
Nested class program: Output:
#include<iostream>
using namespace std; Nested classes in C++
class A { The number is 9
public:
class B { Note:In the function main(), an
private: object of the class A and class B is
int num; defined. Then the functions
public: getdata() and putdata() are called
void getdata(int n) { using the variable obj. This is shown
num = n; below.
}
void putdata() {
cout<<"The number is "<<num;
}
};
};
int main() {
cout<<"Nested classes in C++"<< endl;
A :: B obj;
obj.getdata(9);
obj.putdata();
return 0;
}
Enumeration

• An enumeration is a user-defined data type that


consists of integral constants. To define an
enumeration, keyword enum is used.

• enum season { spring, summer, autumn, winter };


• Here, the name of the enumeration is season.

• And, spring, summer and winter are values of


type season.
Syntax:

enum enumerated-type-name
{
value1, value2, value3…..valueN
};
// C++ Program to Demonstrate the Functioning of Enumerators with an example of Gender
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Defining enum Gender
enum Gender { Male, Female };

// Creating Gender type variable


Gender gender = Male;
switch (gender) {
case Male:
cout << "Gender is Male";
break;
case Female:
cout << "Gender is Female";
break;
default:
cout << "Value can be Male or Female";
}
return 0;
}
Public and private inheritance
• public, protected, and private inheritance have the
following features:
• public inheritance makes public members of the base
class public in the derived class, and the protected
members of the base class remain protected in the
derived class.
• protected inheritance makes the public and protected
members of the base class protected in the derived
class.
• private inheritance makes the public and protected
members of the base class private in the derived class.
• Note: private members of the base class are
inaccessible to the derived class.
Public and private inheritance
• If the inheritance is public , everything that is
aware of Base and Child is also aware that
Child inherits from Base .
• If the inheritance is protected , only Child ,
and its children, are aware that
they inherit from Base .
• If the inheritance is private , no one other
than Child is aware of the inheritance
class Base {
public:
int x;
protected:
int y;
private:
int z;
};

class PublicDerived: public Base {


// x is public
// y is protected
// z is not accessible from PublicDerived
};
class ProtectedDerived: protected Base {
// x is protected
// y is protected
// z is not accessible from ProtectedDerived
};

class PrivateDerived: private Base {


// x is private
// y is private
// z is not accessible from PrivateDerived
};
// C++ program to demonstrate the working of public
inheritance

class PublicDerived : public Base {


#include <iostream>
public:
using namespace std; // function to access protected member from
class Base { Base
private: int getProt() {
int pvt = 1; return prot;
}
};
protected:
int main() {
int prot = 2; PublicDerived object1;
cout << "Private = " << object1.getPVT() << endl;
public: cout << "Protected = " << object1.getProt() << endl;
int pub = 3; cout << "Public = " << object1.pub << endl;
// function to access private member return 0;
}
int getPVT()
{ Output:
return pvt; Private = 1
} Protected = 2
}; Public = 3
// C++ program to demonstrate the working of
protected inheritance class ProtectedDerived : protected Base {
#include <iostream> public:
using namespace std; // function to access protected member from
class Base { Base
private: int getProt() {
return prot;
int pvt = 1;
}
// function to access public member from Base
protected: int getPub() {
int prot = 2; return pub;
}
public: };
int main() {
int pub = 3;
ProtectedDerived object1;
// function to access private member cout << "Private cannot be accessed." << endl;
int getPVT() cout << "Protected = " << object1.getProt() << endl;
{ cout << "Public = " << object1.getPub() << endl;
return pvt; return 0;
} }
Output:
};
Private cannot be accessed.
Protected = 2
Public = 3
// C++ program to demonstrate the working of
private inheritance class PrivateDerived : private Base {
#include <iostream> public:
using namespace std; // function to access protected member from
Base
class Base { int getProt() {
return prot;
private:
}
int pvt = 1; // function to access private member
int getPub() {
protected: return pub;
int prot = 2; }
};
int main() {
public:
PrivateDerived object1;
int pub = 3; cout << "Private cannot be accessed." << endl;
// function to access private member cout << "Protected = " << object1.getProt() << endl;
int getPVT() cout << "Public = " << object1.getPub() << endl;
{ return 0;
return pvt; }
Output:
}
Private cannot be accessed.
}; Protected = 2
Public = 3
Pointers
Pointers
• Pointers are extremely powerful because they
allows you to access addresses and
manipulate their content.
Pointer Variables (or Pointers)
• A pointer variable (or pointer in short) is
basically the same as the other variables,
which can store a piece of data. Unlike normal
variable which stores a value (such as an int,
a double, a char), a pointer stores a memory
address
Declaring pointers
• Pointers must be declared before they can be
used, just like a normal variable.
• The syntax of declaring a pointer is to place
a * in front of the name.
• A pointer is associated with a type (such
as int and double) too.
Declaring pointers
• type *ptr; // Declare a pointer variable
called ptr as a pointer of type
or
type* ptr;
Declaring pointers
• E.g.
int * iPtr;
// Declare a pointer variable called iPtr
pointing to an int (an int pointer)
It contains an address. That address holds an int
value.
double * dPtr; // Declare a double pointer
Initializing Pointers via the address –of-
operator(&)
• The address-of operator (&) operates on a
variable, and returns the address of the
variable.
• For example,
• if number is an int variable, &number returns
the address of the variable number.
• You can use the address-of operator to get the
address of a variable, and assign the address to
a pointer variable.
Initializing Pointers via the address –of-
operator(&)
• E.g.
int number = 88; // An int variable with a value
int * pNumber; // Declare a pointer variable called
pNumber pointing to an int (or int pointer)
pNumber = &number; // Assign the address of the
variable number to pointer pNumber
int * pAnother = &number; // Declare another int
pointer and init to address of the variable number
Initializing Pointers via the address –of-
operator(&)
Program
#include <iostream>
#include <string>
using namespace std;

int main() {
string food = "Pizza";

cout << food << "\n";


cout << &food << "\n";
return 0;
}

Output:
Pizza
0x6dfed4
Program
#include <iostream>
#include <string>
using namespace std;

int main() {
string food = "Pizza"; // A string variable
string* ptr = &food; // A pointer variable that stores the address of food

// Output the value of food


cout << food << "\n";

// Output the memory address of food


cout << &food << "\n";

// Output the memory address of food with the pointer


cout << ptr << "\n";
return 0;
}
Output:
Pizza
0x6dfed4
0x6dfed4
Indirection or Dereferencing Operator (*)

• The indirection operator (or dereferencing


operator) (*) operates on a pointer, and
returns the value stored in the address kept in
the pointer variable.
• For example,
if pNumber is an int pointer,
*pNumber returns the int value "pointed to"
by pNumber.
• int number = 88;
• int * pNumber = &number; // Declare and
assign the address of variable number to pointer
pNumber (0x22ccec)
• cout << pNumber<< endl; // Print the content of
the pointer variable, which contain an address
(0x22ccec)
• cout << *pNumber << endl; // Print the value
"pointed to" by the pointer, which is an int (88)
• Note:- pNumber stores a memory address
location, whereas *pNumber refers to the value
stored in the address kept in the pointer
variable, or the value pointed to by the pointer.
• a variable (such as number) directly references a value,
whereas a pointer indirectly references a value through
the memory address it stores. Referencing a value
indirectly via a pointer is called
indirection or dereferencing.
• the symbol * has different meaning in a declaration
statement and in an expression. When it is used in a
declaration .
e.g.,
• int * pNumber,
it denotes that the name followed is a pointer variable. e.g.,
• *pNumber = 99;
it refers to the value pointed to by the pointer variable.
Program
#include <iostream>
#include <string>
using namespace std;

int main() {
string food = "Pizza"; // Variable declaration
string* ptr = &food; // Pointer declaration

// Reference: Output the memory address of food with the pointer


cout << ptr << "\n";

// Dereference: Output the value of food with the pointer


cout << *ptr << "\n";
return 0;
}
Output:
0x6dfed4
Pizza
Dynamic Memory Management
• The main differences between static allocation and
dynamic allocations are:
• In static allocation, the compiler allocates and deallocates
the storage automatically, and handle memory
management.
• Whereas in dynamic allocation, the programmer, handle
the memory allocation and deallocation
(via new and delete operators).
• You have full control on the pointer addresses and their
contents, as well as memory management.
• Static allocated entities are manipulated through named
variables.
• Dynamic allocated entities are handled through pointers.
Dynamic Memory Management
• Allocates memory dynamically by using new
operator
• Deallocates the memory using delete
operator.
• The new operation returns a pointer to the
memory allocated. The delete operator takes
a pointer (pointing to the memory allocated
via new) as its sole argument.
Dynamic Memory Management
// Pointer initialized with NULL
// Then request memory for the variable
int *p = NULL;
p = new int;

OR

// Combine declaration of pointer


// and their assignment
int *p = new int;
new and delete operator

• Syntax;
new data type;
data-type could be any built-in data type
including an array or any user defined data
types include class or structure.
e.g.
double* pvalue = NULL; // Pointer initialized
with null
pvalue = new double; // Request memory for
the variable
int * p2; // Not initialize, points to somewhere which
is invalid
cout << p2 << endl; // Print address before allocation
p2 = new int; // Dynamically allocate an int and
assign its address to pointer // The pointer gets a
valid address with memory allocated
*p2 = 99;
cout << p2 << endl; // Print address after allocation
cout << *p2 << endl; // Print value point-to
delete p2; // Remove the dynamically allocated
storage
The new operator:
The new operator requests for the memory allocation in heap. If
the sufficient memory is available, it initializes the memory to
the pointer variable and returns its address.

Here is the syntax of new operator in C++ language,

pointer_variable = new datatype;


Here is the syntax to initialize the memory,

pointer_variable = new datatype(value);


Here is the syntax to allocate a block of memory,

pointer_variable = new datatype[size];


//new operator:
#include <iostream>
using namespace std;
int main () {
int *ptr1 = NULL;
ptr1 = new int;
float *ptr2 = new float(223.324);
int *ptr3 = new int[28];
*ptr1 = 28;
cout << "Value of pointer variable 1 : " << *ptr1 << endl;
cout << "Value of pointer variable 2 : " << *ptr2 << endl;
if (!ptr3)
cout << "Allocation of memory failed\n";
else {
for (int i = 10; i < 15; i++)
ptr3[i] = i+1;
cout << "Value of store in block of memory: ";
for (int i = 10; i < 15; i++)
cout << ptr3[i] << " ";
}
return 0;
• Output:
Value of pointer variable 1 : 28
Value of pointer variable 2 : 223.324
Value of store in block of memory: 11 12 13 14
15
//new operator:
if (!ptr3)
#include <iostream> cout << "Allocation of memory failed\n";
using namespace std; else {
int main () { for (int i = 10; i < 15; i++)
ptr3[i] = i+1;
int *ptr1 = NULL; cout << "Value of store in block of memory: ";
ptr1 = new int; for (int i = 10; i < 15; i++)
float *ptr2 = new float(223.324); cout << ptr3[i] << " ";
}
int *ptr3 = new int[28];
return 0;
*ptr1 = 28; }

cout << "Value of pointer variable 1 : " << ptr1 << endl;
cout << "Value of pointer variable 2 : " << ptr2 << endl;
cout << "Value of pointer variable 1 : " << *ptr1 << endl;
cout << "Value of pointer variable 2 : " << *ptr2 << endl;
cout << "Value of pointer variable 3 : " << ptr3 << endl;
cout << "Value of pointer variable 3 : " << *ptr3 << endl;
• Output:
Value of pointer variable 1 : 0x871eb0
Value of pointer variable 2 : 0x871ed0
Value of pointer variable 1 : 28
Value of pointer variable 2 : 223.324
Value of pointer variable 3 : 0x871ef0
Value of pointer variable 3 : 0
The delete operator
The delete operator is used to deallocate the memory.
User has privilege to deallocate the created pointer
variable by this delete operator.

Here is the syntax of delete operator in C++ language,

delete pointer_variable;
Here is the syntax to delete the block of allocated
memory,

delete[ ] pointer_variable;
//delete operator:
#include <iostream>
using namespace std;
int main () {
int *ptr1 = NULL;
ptr1 = new int;
float *ptr2 = new float(299.121);
int *ptr3 = new int(30);
*ptr1 = 28;
cout << "Value of pointer variable 1 : " << *ptr1 << endl;
cout << "Value of pointer variable 2 : " << *ptr2 << endl;
cout << "Value of pointer variable 3 : " << *ptr3 << endl;
delete ptr1;
delete ptr2;
delete[] ptr3;
cout << "Value of pointer variable 1 : " << *ptr1 << endl;
cout << "Value of pointer variable 2 : " << *ptr2 << endl;
cout << "Value of pointer variable 3 : " << *ptr3 << endl;
return 0;
}
• Output:
Value of pointer variable 1 : 28
Value of pointer variable 2 : 299.121
Value of pointer variable 3 : 30
Value of pointer variable 1 : 0
Value of pointer variable 2 : -2.42212e+09
Value of pointer variable 3 : -821010736
Pointers to Objects
• You can access an object either directly, or by using
a pointer to the object.
• To access an element of an object when using the
actual object itself, use the dot operator.
• To access a specific element of an object when
using a pointer to the object, you must use the
arrow operator.
• To declare an object pointer, you use the same
declaration syntax that you would use for any other
pointer type.
Pointers to Objects
student st; 51, Rajesh

student *ptr; void read_data( )

ptr = & st; void print_data( )

st
ptr 2FCD54
Pointers to Objects
• Pointers can be defined to hold the address of an
object, which is created statically or dynamically

Statically created object:


33, Joseph
student *stp;
stp = &st;
void read_data( )
Dynamically created object:
void print_data( )
student *stp;
stp = new student;
st
2FCDA4
Pointers to Objects
• Accessing Members of objects: using arrow pointer
operator ()
Syntax:
ptr_ob j  member_name;
ptr_obj  memberfunction_name( );

Example:
stp  st_name;
stp  read_data ( );
// A simple example using an object int main()
pointer. {
My_Class ob, *p; // declare an object and
#include <iostream> pointer to it
using namespace std;
ob.set_num(1); // access ob directly
ob.show_num();
class My_Class {
int num; p = &ob; // assign p the address of ob
public: p->show_num(); // access ob using pointer
void set_num(int val) {num = val;}
void show_num(); return 0;
}; }

Output:
void My_Class::show_num() 1
{ 1
cout << num << "\n";
}
The this Pointer
• The this pointer points to the object that
invoked the function

• When a member function is called with an


object, it is automatically passed an implicit
argument that is a pointer to the invoking
object (that is, the object on which the
function is called).
The this Pointer
• Accessing Members of objects:
Syntax:
obj . memberfunction_name( );

this pointer points to st object


Example:
st . read_data ( );
Pointers Vs Array
• Pointer can not hold address of single variable
only but it also hold address of cells of array.
• E.g
int arr[5];
int *ptr;
ptr=arr;
(store the address of first element of array)
Accessing arrays using pointer
• Pointer to an array is also known as array
pointer. We are using the pointer to access the
components of the array.
• E.g .
int a[3] = {3, 4, 5 };
int *ptr = a;
We have a pointer ptr that focuses to the 0th
component of the array.
Arrays of pointers
• “Array of pointers” is an array of the pointer
variables. It is also known as pointer arrays.
Syntax:-
int *var_name[array_size];
Eg.
int *ptr[3];
Accessing arrays using pointer
• Declare a pointer that can point to whole
array rather than just a single component of
the array.
Syntax:
data type (*var name)[size of array];
e.g.
int (*ptr)[5];
S. No. Array Pointer

Pointers are declared as type *


1. Arrays are declared as type var_name[size];
var_name;

2. Collection of elements of similar data type. Store the address of another variable.

The array can be initialized at the time of Pointers cannot be initialized at


3.
definition. definition.

The size of the array decides the number of The pointer can store the address of
4.
elements it can store. only one variable.

5. Arrays are allocated at compile time. Pointers are allocated at run-time.

6. Memory allocation is contiguous. Memory allocation is random.

Arrays are static in nature i.e. they cannot be Pointers are dynamic in nature i.e.
7.
resized according to the user requirements. memory allocated can be resized later.

8. An array of pointers can be created. A pointer to an array can be created.


Accessing arrays using pointer
Accessing arrays using pointer
• 1D array of size N(= 5) is created and the base
address is assigned to the variable P. If the below
statement is written then the output is 1000. (e.g.
cout << P;)
• If the value in the 1000th address is wanted then
dereferenced it using the * (asterisk) symbol as
illustrated below:
(e.g. cout << *P;// It is the same as P[0]. The
output is 23.)
Basic Pointer Arithmetic:
Below is some points regarding Pointer Arithmetic:

*(P + 1):
P = 1000 and 1 = sizeof(int) = 4 bytes.
Hence, *(1004) and dereferencing by * (asterisk) symbol. Now,
the final result is 38.

*(P) + 1:
P = 1000
Hence, *(1000) and dereferencing by * (asterisk) symbol and
then by adding 1 modifies the result to 23 + 1 = 24.
// C++ program to illustrate the // Print the values using pointers
concepts cout << *p << endl;
cout << *p + 1 << endl;
// of creating 1D array of pointers
cout << *(p + 1) << endl;
#include <iostream> cout << 2[p] << endl;
using namespace std; cout << p[2] << endl;
int main() cout << 3[p] << endl;
{ cout << p[4] << endl;
// Dynamically creating the array *p++;
// Pointing to next location
// of size = 5
cout << *p;
int* p = new int[5];
return 0;
// Initialize the array p[] as }
// {10, 20, 30, 40, 50}
for (int i = 0; i < 5; i++) {
p[i] = 10 * (i + 1);
}
Output
• 10
• 11
• 20
• 30
• 30
• 40
• 50
• 20
Dynamic 2D Array of Pointers in C++:
• A dynamic array of pointers is basically an array of
pointers where every array index points to a memory
block. This represents a 2D view in our mind. But
logically it is a continuous memory block.
• Syntax:<dataType> **<Pointer name> = new
<dataType> *[<size>];
• Ex: int **P = new int *[4];
• The *(asterisk) symbol defines the level of the pointer,
one * means one level of pointers, where ** implies
two levels of pointers, and so on. Also, the level of the
pointer must be the same as the dimensional array
you want to create dynamically.
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.
• Int **var;
Approach: Create a 1D array of pointers.
1-D Array

Now, create the column as array of pointers for each row


as:
P[0] = new int [3];
P[1] = new int [3];
P[2] = new int [3];
The 1D array of pointers are pointing to a memory block(size is mentioned). Basically,
P[0], …, P[3] are pointing to a 1D array of integers.
Accessing the array elements:

*P is equal to P[0] which is the address of the 1st row, 1st column is &P[0][0] = 3000.
*(P + 1) is equal to ‘P‘ is 1000 + 1(sizeof int) = 1004 and * means dereferencing. So
the value stored at the address is printed i.e., *1004 = 4000.
*(P + 1) + 2 is same as above case but +2 means (&P[1] + 2) is equal to &P[1] [2] =
4008.
*(*(P + 1) + 2) is same as above case but that first asterisk ‘*(….)’ means
dereferencing that address. Therefore, the result is equal to the value in &P[1][2] =
*(4008) = 54.
Pointers to pointers
// C program to demonstrate pointer to pointer
#include <iostream>
using namespace std;
int main ()
{
int var;
int *ptr;
int **pptr;
var = 3000;
ptr = &var;
pptr = &ptr;
cout << "Value of var :" << var << endl;
cout << "Value of ptr :" << ptr << endl;
cout << "Value available at *ptr :" << *ptr << endl;
cout << "Value available at pptr :" << pptr << endl;
cout << "Value available at **pptr :" << **pptr << endl;
return 0;
}
• Output:
Value of var :3000
Value of ptr :0x7ffe54d98a9c
Value available at *ptr :3000
Value available at pptr :0x7ffe54d98aa0
Value available at **pptr :3000
// C++ program to illustrate the // Creating N sized int memory
concepts // block
// of creating 2D array of pointers for (int j = 0; j < N; j++, x++) {

p[i][j] = 10 * x;
#include <iostream>
using namespace std; // The above statement can
// Driver Code // also be written as:
int main() // *(*(p+i)+j) = 10 * x
{ }
int N = 3; }
// Print the values using pointers
// Creating the array of pointers
cout << *p << endl;
// of size N cout << **p << endl;
int** p = new int*[N]; cout << *p + 1 << endl;
int x = 1; cout << **p + 1 << endl;

// For multiplying return 0;


}
for (int i = 0; i < N; i++) {
p[i] = new int[N];
Output:

0x158de90
10
0x158de94
11
Function pointer
• Function pointers are similar, except that
instead of pointing to variables, they point to
functions!
• Syntax for Declaration
• The following is the syntax for the declaration
of a function pointer:

• int (*FuncPtr) (int,int);


Pointers to function
e.g.
int (*fcnPtr)();

- fcnPtr is a pointer to a function that has no parameters


and returns an integer. It can point to any function that
matches this type.

Int *ptr;
Int *ptr[5];
Int (*ptr)();
//Program for function pointer declaration
#include <iostream>
using namespace std;
int add(int a , int b)
{
return a+b;
}
int main()
{
int (*funcptr)(int,int); // function pointer declaration
funcptr=add; // funcptr is pointing to the add function
int sum=funcptr(5,5);
cout << "value of sum is :" <<sum<<endl;
return 0;
}

Output:
value of sum is :10
Null pointer
• 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.
Null pointer program:

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

Output: The value of ptr is 0


Void pointer
• A void pointer is a pointer that can point to
any type of object, but does not know what
type of object it points to.
• A void pointer must be explicitly cast into
another type of pointer to be dereferenced.
Void pointer
• The void pointer, also known as the generic
pointer, is a special type of pointer that can be
pointed at objects of any data type.
• A void pointer is declared like a normal
pointer, using the void keyword as the
pointer’s type:
Void *ptr;
Void pointer program
#include <iostream>
using namespace std;

int main()
{
int a = 10;
char b = 'x';

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


cout<<p<<endl;
p = &b; // void pointer holds address of char 'b'
cout<<*p<<endl;
}

Output:
error: ‘void*’ is not a pointer-to-object type
12 | cout<<*p<<endl;
Void pointer program
#include <iostream>
using namespace std;

int main()
{
int a = 10;
char b = 'x';

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


cout<<p<<endl;
p = &b; // void pointer holds address of char 'b'
cout<<p<<endl;
}

Output:
0x7ffd25ba9374
0x7ffd25ba9373
Void pointer program
#include <iostream>
using namespace std;

int main()
{
int a = 10;
char b = 'x';

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


cout<<p<<endl;
p = &a; // void pointer holds address of char 'b'
cout<<*(int *)p<<endl;
}

Output:
0x7fff5575e717
10
Pointers to base class
• Pointer is a data type that stores the address
of other data types.
• The pointer of Base Class pointing different
object of derived class:
Approach:

• 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, value is changed.
// C++ program:
var_base << endl;
#include <iostream>
cout << "Displaying Derived "
using namespace std; << " class variable var_derived: "
class BaseClass { << var_derived << endl;
public: }
int var_base; };

void display()
{
cout << "Displaying Base class"
<< " variable var_base: " << var_base <<
endl;
}
};
class DerivedClass : public BaseClass {
public:
int var_derived;
void display()
{
cout << "Displaying Base class"
<< "variable var_base: " <<
// Driver Code
int main()
{
// Pointer to base class
BaseClass* base_class_pointer; return 0;
BaseClass obj_base; }
DerivedClass obj_derived;
// Pointing to derived class
base_class_pointer = &obj_derived;
base_class_pointer->var_base = 34;

// Calling base class member function


base_class_pointer->display();

base_class_pointer->var_base = 3400;
base_class_pointer->display();

DerivedClass* derived_class_pointer;
derived_class_pointer = &obj_derived;
derived_class_pointer->var_base = 9448;
derived_class_pointer->var_derived = 98;
derived_class_pointer->display();
Output:
Displaying Base class variable var_base: 34
Displaying Base class variable var_base:
3400
Displaying Base classvariable var_base: 9448
Displaying Derived class variable
var_derived: 98

You might also like