SlideShare a Scribd company logo
OOPS THROUGH C++
1
Dr. Chandra Sekhar Sanaboina
Assistant Professor
Department of Computer Science and Engineering
University College of Engineering Kakinada
Jawaharlal Nehru Technological University Kakinada
Website: https://drcs.info
Youtube Link:
https://www.youtube.com/watch?v=nPjHraTbPeY&list=PLT1ngltOnlJiHbzVvjkU8VzQt9oam8ji4
UNIT – IV
POINTERS
&
BINDING POLYMORPHISMS AND VIRTUAL FUNCTIONS
2
AGENDA
• Pointer
• Features of Pointers
• Pointer Declaration
• Pointer to Class
• Pointer Object
• The this Pointer
• Pointer to Derived Classes and Base Class
• Binding Polymorphisms and Virtual Functions
• Introduction
• Binding in C++
• Virtual Functions
• Rules for Virtual Function
• Virtual Destructor
3
POINTERS
4
POINTERS
• Introduction:
• Every variable has a memory location and every memory location has its
address defined which can be accessed using ampersand (&) operator
which denotes an address in memory
• A pointer is a variable whose value is the address of another variable
• Like any variable or constant, you must declare a pointer before you can
work with it
• Syntax:
• type *variable_name;
• type is the pointer's base type it must be a valid C++ type
• var-name is the name of the pointer variable
• Benefits:
• Some C++ tasks are performed more easily with pointers
• Some tasks, such as dynamic memory allocation cannot be performed without
them
• More than one variable can be modified and returned by function using
pointers.
• Pointers help in simplifying the complexity of the program.
• Pointers increase the execution speed.
5
FEATURES OF POINTERS
• Pointers save memory space
• Allocates memory as and when required
• Execution time with pointers is faster
• because data are manipulated with the address, that is, direct access to memory location
• Memory is accessed efficiently with the pointers
• The pointer assigns and releases the memory as well. Hence it can be said the Memory of pointers is
dynamically allocated
• Pointers are used with data structures. They are useful for representing two-dimensional and multi-
dimensional arrays
• An array, of any type can be accessed with the help of pointers, without considering its subscript
range
• Pointers are used for file handling
• Pointers are used to allocate memory dynamically
• In C++, a pointer declared to a base class could access the object of a derived class. However, a
pointer to a derived class cannot access the object of a base class 6
USES OF POINTERS
• To pass arguments by reference
• For accessing array elements
• To return multiple values
• Dynamic memory allocation
• To implement data structures
• To do system level programming where memory
addresses are useful
7
POINTERS CONTD…
• int *ip; // pointer to an integer
• double *dp; // pointer to a double
• float *fp; // pointer to a float
• char *ch // pointer to character
• Note: The only difference between pointers of different
data types is the data type of the variable or constant
that the pointer points to
8
ADDRESSES IN C++
• When we create a variable in our C++ program, it is
assigned some space in the computer memory
• The value of this variable is stored in the assigned
location
• To know the location in the computer memory where the
data is stored, C++ provides the & (reference) operator
• The operator returns the address that a variable occupies
• Example: I
• If x is a variable, &x returns the address of the variable
9
REFERENCE OPERATOR (&) AND
DEFERENCE OPERATOR (*)
• The reference operator (&) returns the variable's address
• The dereference operator (*) helps us get the value that
has been stored in a memory address
• Example:
• If we have a variable given the name num, stored in the
address 0x234 and storing the value 27.
• The reference operator (&) will return 0x234.
• The dereference operator (*) will return 27.
10
POINTERS PROGRAMMING 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;
}
11
NULL POINTER
12
NULL POINTER
• If there is no exact address that is to be assigned, then the pointer
variable can be assigned a NULL
• It should be done during the declaration
• Such a pointer is known as a NULL pointer
• Its value is zero and is defined in many standard libraries like iostream
• Example:
#include <iostream>
using namespace std;
int main() {
int *ip = NULL;
cout << "Value of ip is: " << ip;
return 0;
}
13
POINTER TO CLASS
14
POINTER TO CLASS
• A class pointer is a pointer variable that stores address of
an object of a class
• A pointer to a C++ class is done exactly the same way as a
pointer to a structure
• To access members of a pointer to a class we use the member
access operator -> operator, just as we do with pointers to
structures
• As with all pointers, you must initialize the pointer before using it
15
POINTER TO CLASS CONTD…
16
POINTER TO CLASS EXAMPLE
#include <iostream>
using namespace std;
class Box {
public:
Box(double l = 2.0, double b = 2.0, double h =
2.0) {
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
}
double Volume() {
return length * breadth * height;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main(void) {
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
Box *ptrBox; // Declare pointer to a class.
ptrBox = &Box1;
cout << "Volume of Box1: " << ptrBox->Volume()
<< endl;
ptrBox = &Box2;
cout << "Volume of Box2: " << ptrBox->Volume()
<< endl;
return 0;
}
17
POINTER TO OBJECTS
(THIS POINTER)
18
POINTERS TO OBJECTS – THIS POINTER
• A Variable that holds the address is called
a Pointer variable or simply pointer
• Similarly, Objects can also have an address, so there is
also a pointer that can point to the address of
an Object
• That Pointer is Known as this Pointer
19
THIS POINTER
• Every object in C++ has access to its own address through an important
pointer called this pointer
• The this pointer is an implicit parameter to all member functions.
Therefore, inside a member function, this may be used to refer to the
invoking object
• Friend functions do not have a this pointer, because friends are not
members of a class
• Only member functions have a this pointer
20
THIS POINTER CONTD…
• this is a keyword that refers to the current instance of the class
• 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
• There can be 3 main usage of this keyword in C++
• It can be used to pass current object as a parameter to
another method
• It can be used to refer current class instance variable
• It can be used to implement chained function calls in C++
21
THIS POINTER EXAMPLE
#include <iostream>
using namespace std;
class Employee {
public:
int id;
string name;
float salary;
Employee(int id, string name, float sala
ry)
{
this->id = id;
this->name = name;
this->salary = salary;
}
void display()
{
cout<<id<<" "<<name<<" "<<sal
ary<<endl;
}
};
int main(void) {
Employee e1 =Employee(101, "Sonoo", 89
0000); //creating an object of Employee
Employee e2=Employee(102, "Nakul", 590
00); //creating an object of Employee
e1.display();
e2.display();
return 0;
}
22
THIS POINTER EXAMPLE
#include <iostream>
using namespace std;
class Box {
public:
Box(double l = 2.0, double b = 2.0,
double h = 2.0) {
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
}
double Volume() {
return length * breadth * height;
}
int compare(Box box) {
return this->Volume() > box.Volume();
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main(void) {
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
if(Box1.compare(Box2)) {
cout << "Box2 is smaller than Box1"
<<endl;
} else {
cout << "Box2 is equal to or larger than
Box1" <<endl;
}
return 0;
}
23
CHAINED FUNCTION CALLS
24
CHAINED FUNCTION CALLS
• When a reference to a local object is returned, the returned
reference can be used to chain function calls on a single
object
Test& Test::func ()
{
// Some processing
return *this;
}
25
CHAINED FUNCTION CALLS EXAMPLE
#include<iostream>
using namespace std;
class Test
{
private:
int x;
int y;
public:
Test(int x = 0, int y = 0) { this->x = x; this->y =
y; }
Test &setX(int a) { x = a; return *this; }
Test &setY(int b) { y = b; return *this; }
void print() { cout << "x = " << x << " y = " <<
y << endl; }
};
int main()
{
Test obj1(5, 5);
// Chained function calls. All calls modify the
same object
// as the same object is returned by reference
obj1.setX(10).setY(20);
obj1.print();
return 0;
}
26
SMART POINTERS
27
SMART POINTERS
• Problem with Normal Pointers:
• Every time we make use of Dynamic Memory Allocation it will
create an object for each and every object we create, but not
it’s deleting.
• When these pointers are not deleted it will lead to leakage of
memory from the heap memory
• So slowly the entire heap memory may become unused because
it’s infinite. So at one stage because of a lack of heap memory,
the program will crash
28
SMART POINTERS CONTD…
• What are Smart Pointers?
• The problem with heap memory is that when you don’t need it you
must deallocate
• So mostly the programmers are too lazy in writing the code for
deallocation of objects and that causes severe problem like memory
leak which will cause the program to crash
• The languages like Java, C#, .Net Framework they provide
a garbage collection mechanism to deallocate the object which is
not in use
• In C++ 11, it introduces smart pointers that automatically manage
memory and they will deallocate the object when they are not in use
when the pointer is going out of scope automatically it’ll deallocate the
memory 29
SMART POINTERS CONTD…
• Using Smart Pointers, we can make pointers to work in a way that we don’t
need to explicitly call delete
• A smart pointer is a wrapper class over a pointer with an operator like * and ->
overloaded
• The objects of smart pointer class look like a pointer but can do many things
that a normal pointer can’t like automatic destruction
• The idea is to take a class with a pointer, destructor and overloaded
operators like * and ->
• Since the destructor is automatically called when an object goes out of scope,
the dynamically allocated memory would automatically be deleted
30
SMART POINTERS CONTD…
#include <iostream>
using namespace std;
class SmartPtr {
int* ptr;
public:
explicit SmartPtr(int* p = NULL) { ptr
= p; }
// Destructor
~SmartPtr() { delete (ptr); }
// Overloading dereferencing
operator
int& operator*() { return *ptr; }
};
int main()
{
SmartPtr ptr(new int());
*ptr = 20;
cout << *ptr;
// We don't need to call delete ptr:
when the object ptr goes out of scope, the
destructor for it is automatically called and
destructor does delete ptr
return 0;
}
31
BINDING
32
BINDING
• Introduction
• The binding means the process of converting identifiers into addresses
• For each variables and functions this binding is done
• For functions it is matching the call with the right function definition by the
compiler
• The binding is done either at compile time or at runtime
33
TYPES OF BINDING
34
BINDING CONTD…
• Types of Binding in C++
• Early Binding
• Late Binding
35
EARLY BINDING
36
EARLY BINDING
• Early Binding
• This is compile time polymorphism
• It is also known as Static Binding or Compile-time Binding
• The compiler/linker directly associates an address to the function
call
• Function overloading it is an example of early binding
• Function overriding in which the base and derived classes have
functions with the same name, parameters and return type is also
an example of early binding
• It is the default binding process in C++
37
EARLY BINDING EXAMPLE
#include<iostream>
using namespace std;
class Base {
public:
void display() {
cout<<" In Base class" <<endl;
}
};
class Derived: public Base {
public:
void display() {
cout<<"In Derived class" << endl;
}
};
int main(void) {
Base *base_pointer = new Derived;
base_pointer->display();
return 0;
}
38
EARLY BINDING EXAMPLE 2
#include <iostream>
using namespace std;
class Animals
{
public:
void sound()
{
cout << "This
is parent class" << endl;
}
};
class Dogs : public Animals
{
public:
void sound()
{
cout << "Dogs
bark" << endl;
}
};
int main()
{
Animals *a;
Dogs d;
a= &d;
a -> sound(); // early binding
return 0;
}
39
LATE BINDING
40
LATE BINDING
• Late Binding
• This is run time polymorphism
• It is also known as Dynamic Binding or Runtime Binding
• In this type of binding the compiler adds code that identifies the
object type at runtime then matches the call with the right function
definition
• This is achieved by using virtual function 41
VIRTUAL FUNCTIONS
42
VIRTUAL FUNCTION
• A C++ virtual function is a member function in the base class that you
redefine in a derived class
• It is declared using the virtual keyword
• A 'virtual' is a keyword preceding the normal declaration of a function.
• It is used to tell the compiler to perform dynamic linkage or late binding
on the function
• There is a necessity to use the single pointer to refer to all the objects of
the different classes. So, we create the pointer to the base class that
refers to all the derived objects. But, when base class pointer contains the
address of the derived class object, always executes the base class
function. This issue can only be resolved by using the 'virtual' function.
• When the function is made virtual, C++ determines which function is to
be invoked at the runtime based on the type of the object pointed by the
base class pointer
43
RULES FOR VIRTUAL FUNCTION
• Virtual functions must be members of some class
• Virtual functions cannot be static members
• They are accessed through object pointers
• They can be a friend of another class
• A virtual function must be defined in the base class, even though it
is not used
• The prototypes of a virtual function of the base class and all the
derived classes must be identical. If the two functions with the
same name but different prototypes, C++ will consider them as the
overloaded functions
• We cannot have a virtual constructor, but we can have a virtual
destructor 44
LATE BINDING EXAMPLE
#include<iostream>
using namespace std;
class Base {
public:
virtual void display() {
cout<<"In Base class" << endl;
}
};
class Derived: public Base {
public:
void display() {
cout<<"In Derived class" <<endl;
}
};
int main() {
Base *base_pointer = new Derived;
base_pointer->display();
return 0;
}
45
LATE BINDING EXAMPLE 2
#include <iostream>
using namespace std;
class Animals
{
public:
virtual void sound()
{
cout << "This is
parent class" << endl;
}
};
class Dogs : public Animals
{
public:
void sound()
{
cout << "Dogs
bark" << endl;
}
};
int main()
{
Animals *a;
Dogs d;
a= &d;
a -> sound();
return 0;
}
46
LATE BINDING CONTD…
• We can also call private function of derived class from a base class
pointer by declaring that function in the base class as virtual
• Compiler checks if the members of a class are private, public or
protected only at compile time and not at runtime
• Since our function is being called at runtime, so we can call any
type of function, private or public
47
LATE BINDING EXAMPLE 2
#include <iostream>
using namespace std;
class Animals
{
public:
virtual void sound()
{
cout << "This is
parent class" << endl;
}
};
class Dogs : public Animals
{
private:
virtual void sound()
{
cout << "Dogs
bark" << endl;
}
};
int main()
{
Animals *a;
Dogs b;
a = &b;
a->sound();
return 0;
}
48
PURE VIRTUAL FUNCTIONS
49
PURE VIRTUAL FUNCTIONS
• Pure virtual function is a virtual function which has no
definition
• Pure virtual functions are also called abstract functions
• To create a pure virtual function, we assign a value 0
• Syntax:
• virtual void func_name() = 0;
50
PURE VIRTUAL FUNCTIONS CONTD…
• A virtual function is not used for performing any task. It only
serves as a placeholder
• When the function has no definition, such function is known as
"do-nothing" function
• The "do-nothing" function is known as a pure virtual
function. A pure virtual function is a function declared in the
base class that has no definition relative to the base class
• A class containing the pure virtual function cannot be used to
declare the objects of its own, such classes are known as
abstract base classes
• The main objective of the base class is to provide the traits to
the derived classes and to create the base pointer used for
achieving the runtime polymorphism 51
ABSTRACT CLASSES
52
ABSTRACT CLASS
• An abstract class is a class whose instances (objects) can't be
made
• We can only make objects of its subclass (if they are not
abstract)
• Abstract class is also known as abstract base class.
• An abstract class has at least one abstract function (pure
virtual function)
53
ABSTRACT CLASS EXAMPLE
#include <iostream>
using namespace std;
class Employee // abstract base class
{
virtual int getSalary() = 0; // pure virtual
function
};
class Developer : public Employee
{
int salary;
public:
Developer(int s)
{
salary = s;
}
int getSalary()
{
return salary;
}
};
class Driver : public Employee
{
int salary;
public:
Driver(int t)
{
salary = t;
}
int getSalary()
{
return salary;
}
};
int main()
{
Developer d1(5000);
Driver d2(3000);
int a, b;
a = d1.getSalary();
b = d2.getSalary();
cout << "Salary of Developer : " << a <<
endl;
cout << "Salary of Driver : " << b << endl;
return 0;
}
54
ABSTRACT CLASS CONTD…
• Subclasses of an abstract base class must define the
abstract method, otherwise, they will also become abstract
classes
• In an abstract class, we can also have other functions and
variables apart from pure virtual function
55
ABSTRACT CLASS EXAMPLE
#include <iostream>
using namespace std;
class Animals
{
public:
virtual void sound() = 0;
};
class Dogs : public Animals
{
public:
void sound()
{
cout << "Dogs bark"
<< endl;
}
};
class Cats : public Animals
{
public:
void sound()
{
cout << "Cats meow"
<< endl;
}
};
class Pigs
{
public:
void sound()
{
cout << "Pigs snort"
<< endl;
}
};
int main()
{
Dogs d;
Cats c;
Pigs p;
d.sound();
c.sound();
p.sound();
return 0;
}
56
DESTRUCTORS
57
DESTRUCTOR
• A destructor in C++ is a member function of a class used to free the
space occupied by or delete an object of the class that goes out of
scope
• A destructor has the same name as the name of the constructor
function in a class, but the destructor uses a tilde (~) sign before its
function name
58
VIRTUAL DESTRUCTOR
59
VIRTUAL DESTRUCTOR
• A virtual destructor is used to free up the memory space allocated by the
derived class object or instance while deleting instances of the derived
class using a base class pointer object
• A base or parent class destructor use the virtual keyword that ensures
both base class and the derived class destructor will be called at run time,
but it called the derived class first and then base class to release the space
occupied by both destructors
60
WHY VIRTUAL DESTRUCTORS
• When an object in the class goes out of scope or the execution of the main() function
is about to end, a destructor is automatically called into the program to free up the
space occupied by the class
• When a pointer of the base class is deleted that points to the derived class, only the
parent class destructor is called due to the early bind by the compiler
• In this way, it skips calling the derived class destructor, which leads to memory leaks
issue in the program
• When we use virtual keyword preceded by the destructor tilde (~) sign inside the base
class, it guarantees that first the derived class destructor is called and then the base
class destructor is called to release the space occupied by both destructors in the
inheritance class
61
WITHOUT VIRTUAL DESTRUCTORS EXAMPLE
#include<iostream>
using namespace std;
class Base
{
public:
Base() // Constructor function.
{
cout<< "n Constructor Base class";
}
~Base() // Destructor function
{
cout<< "n Destructor Base class";
}
};
Output:
Constructor Base Class
Constructor Derived Class
Destructor Base Class
class Derived: public Base
{
public:
Derived() // Constructor function
{
cout << "n Constructor Derived class" ;
}
~Derived() // Destructor function
{
cout << "n Destructor Derived class" ;
}
};
int main()
{
Base *bptr = new Derived; // Create a base class pointer o
bject
delete bptr; /* Here pointer object is called to delete the
space occupied by the destructor.*/
}
62
WITH VIRTUAL DESTRUCTORS EXAMPLE
#include<iostream>
using namespace std;
class Base
{
public:
Base() // Constructor member function.
{
cout << "n Constructor Base class"; // It prints f
irst.
}
virtual ~Base() // Define the virtual destructor func
tion to call the Destructor Derived function.
{
cout << "n Destructor Base class"; /
}
};
Output:
Constructor Base Class
Constructor Derived Class
Destructor Derived Class
Destructor Base Class
class Derived: public Base
{
public:
Derived() // Constructor function.
{
cout << "n Constructor Derived class" ; /* After p
rint the Constructor Base, now it will prints. */
}
~Derived() // Destructor function
{
cout << "n Destructor Derived class"; /* The virt
ual Base Class? Destructor calls it before calling the B
ase Class Destructor. */
}
};
int main()
{
Base *bptr = new Derived; // A pointer object ref
erence the Base class.
delete bptr; // Delete the pointer object.
}
63
PURE VIRTUAL DESTRUCTORS
64
PURE VIRTUAL DESTRUCTORS
• Pure Virtual Destructors are legal in C++
• Pure virtual Destructors must be defined, which is against the
pure virtual behavior
• The only difference between Virtual and Pure Virtual Destructor
is, that pure virtual destructor will make its Base class
Abstract, hence you cannot create object of that class
• There is no requirement of implementing pure virtual
destructors in the derived classes
65
PURE VIRTUAL DESTRUCTOR EXAMPLE
class Base
{
public:
virtual ~Base() = 0; // Pure Virtual
Destructor
};
// Definition of Pure Virtual Destructor
Base::~Base()
{
cout << "Base Destructorn";
}
class Derived:public Base
{
public:
~Derived()
{
cout<< "Derived Destructor";
}
};
int main()
{
Base* b = new Derived; // Upcasting
delete b;
}
66
THE END
67
Ad

More Related Content

What's hot (20)

Pointers in c language
Pointers in c languagePointers in c language
Pointers in c language
Tanmay Modi
 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
Mohammed Sikander
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
Vineeta Garg
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
Burhan Ahmed
 
Array Of Pointers
Array Of PointersArray Of Pointers
Array Of Pointers
Sharad Dubey
 
Structure in c
Structure in cStructure in c
Structure in c
Prabhu Govind
 
arrays and pointers
arrays and pointersarrays and pointers
arrays and pointers
Samiksha Pun
 
Pointer arithmetic in c
Pointer arithmetic in c Pointer arithmetic in c
Pointer arithmetic in c
sangrampatil81
 
C++ Pointers
C++ PointersC++ Pointers
C++ Pointers
Chaand Sheikh
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
Appili Vamsi Krishna
 
C pointer
C pointerC pointer
C pointer
University of Potsdam
 
Decision Making and Looping
Decision Making and LoopingDecision Making and Looping
Decision Making and Looping
Munazza-Mah-Jabeen
 
Python : Data Types
Python : Data TypesPython : Data Types
Python : Data Types
Emertxe Information Technologies Pvt Ltd
 
Pointers in c
Pointers in cPointers in c
Pointers in c
Mohd Arif
 
Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
Jasleen Kaur (Chandigarh University)
 
Call by value or call by reference in C++
Call by value or call by reference in C++Call by value or call by reference in C++
Call by value or call by reference in C++
Sachin Yadav
 
POINTERS IN C
POINTERS IN CPOINTERS IN C
POINTERS IN C
Neel Mungra
 
Pointer in C
Pointer in CPointer in C
Pointer in C
bipchulabmki
 
Pointers in c - Mohammad Salman
Pointers in c - Mohammad SalmanPointers in c - Mohammad Salman
Pointers in c - Mohammad Salman
MohammadSalman129
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
Tasnima Hamid
 

Similar to Object Oriented Programming using C++ - Part 4 (20)

Lecture2.ppt
Lecture2.pptLecture2.ppt
Lecture2.ppt
Sabaunnisa3
 
FUNCTIONS, CLASSES AND OBJECTS.pptx
FUNCTIONS, CLASSES AND OBJECTS.pptxFUNCTIONS, CLASSES AND OBJECTS.pptx
FUNCTIONS, CLASSES AND OBJECTS.pptx
DeepasCSE
 
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxCONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
DeepasCSE
 
Chp3(pointers ref)
Chp3(pointers ref)Chp3(pointers ref)
Chp3(pointers ref)
Mohd Effandi
 
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each OtherIntro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Blue Elephant Consulting
 
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
sindhus795217
 
C# 7 development
C# 7 developmentC# 7 development
C# 7 development
Fisnik Doko
 
C
CC
C
Jerin John
 
Nitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptxNitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptx
shivam460694
 
Data structure and Algorithms (C++).pptx
Data structure and Algorithms (C++).pptxData structure and Algorithms (C++).pptx
Data structure and Algorithms (C++).pptx
ammarasalmanqureshi7
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
TAlha MAlik
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
temkin abdlkader
 
chapter03.ppt easy words to understand and
chapter03.ppt easy words to understand andchapter03.ppt easy words to understand and
chapter03.ppt easy words to understand and
RehaanZaina1
 
Programming fundamentals 2:pointers in c++ clearly explained
Programming fundamentals 2:pointers in c++ clearly explainedProgramming fundamentals 2:pointers in c++ clearly explained
Programming fundamentals 2:pointers in c++ clearly explained
hozaifafadl
 
18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator
SAFFI Ud Din Ahmad
 
C++_notes.pdf
C++_notes.pdfC++_notes.pdf
C++_notes.pdf
HimanshuSharma997566
 
c++ UNIT II.pptx
c++ UNIT II.pptxc++ UNIT II.pptx
c++ UNIT II.pptx
Kongunadu College of Engineering and Technology
 
FYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptxFYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptx
sangeeta borde
 
Arrry structure Stacks in data structure
Arrry structure Stacks  in data structureArrry structure Stacks  in data structure
Arrry structure Stacks in data structure
lodhran-hayat
 
Pointer in C++
Pointer in C++Pointer in C++
Pointer in C++
Mauryasuraj98
 
FUNCTIONS, CLASSES AND OBJECTS.pptx
FUNCTIONS, CLASSES AND OBJECTS.pptxFUNCTIONS, CLASSES AND OBJECTS.pptx
FUNCTIONS, CLASSES AND OBJECTS.pptx
DeepasCSE
 
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxCONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
DeepasCSE
 
Chp3(pointers ref)
Chp3(pointers ref)Chp3(pointers ref)
Chp3(pointers ref)
Mohd Effandi
 
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each OtherIntro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Blue Elephant Consulting
 
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf22 scheme  OOPs with C++ BCS306B_module2.pdfmodule2.pdf
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
sindhus795217
 
C# 7 development
C# 7 developmentC# 7 development
C# 7 development
Fisnik Doko
 
Nitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptxNitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptx
shivam460694
 
Data structure and Algorithms (C++).pptx
Data structure and Algorithms (C++).pptxData structure and Algorithms (C++).pptx
Data structure and Algorithms (C++).pptx
ammarasalmanqureshi7
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
TAlha MAlik
 
chapter03.ppt easy words to understand and
chapter03.ppt easy words to understand andchapter03.ppt easy words to understand and
chapter03.ppt easy words to understand and
RehaanZaina1
 
Programming fundamentals 2:pointers in c++ clearly explained
Programming fundamentals 2:pointers in c++ clearly explainedProgramming fundamentals 2:pointers in c++ clearly explained
Programming fundamentals 2:pointers in c++ clearly explained
hozaifafadl
 
18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator
SAFFI Ud Din Ahmad
 
FYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptxFYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptx
sangeeta borde
 
Arrry structure Stacks in data structure
Arrry structure Stacks  in data structureArrry structure Stacks  in data structure
Arrry structure Stacks in data structure
lodhran-hayat
 
Ad

More from University College of Engineering Kakinada, JNTUK - Kakinada, India (9)

Machine Learning - Implementation with Python - 4.pdf
Machine Learning - Implementation with Python - 4.pdfMachine Learning - Implementation with Python - 4.pdf
Machine Learning - Implementation with Python - 4.pdf
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
Machine Learning - Implementation with Python - 3.pdf
Machine Learning - Implementation with Python - 3.pdfMachine Learning - Implementation with Python - 3.pdf
Machine Learning - Implementation with Python - 3.pdf
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
Machine Learning - Implementation with Python - 2
Machine Learning - Implementation with Python - 2Machine Learning - Implementation with Python - 2
Machine Learning - Implementation with Python - 2
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
Machine Learning - Implementation with Python - 1
Machine Learning - Implementation with Python - 1Machine Learning - Implementation with Python - 1
Machine Learning - Implementation with Python - 1
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
Chandu cyber security career path
Chandu cyber security career pathChandu cyber security career path
Chandu cyber security career path
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
Object Oriented Programming using C++ - Part 1
Object Oriented Programming using C++ - Part 1Object Oriented Programming using C++ - Part 1
Object Oriented Programming using C++ - Part 1
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
Object Oriented Programming using C++ - Part 2
Object Oriented Programming using C++ - Part 2Object Oriented Programming using C++ - Part 2
Object Oriented Programming using C++ - Part 2
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
Object Oriented Programming using C++ - Part 5
Object Oriented Programming using C++ - Part 5Object Oriented Programming using C++ - Part 5
Object Oriented Programming using C++ - Part 5
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
Object Oriented Programming using C++ - Part 3
Object Oriented Programming using C++ - Part 3Object Oriented Programming using C++ - Part 3
Object Oriented Programming using C++ - Part 3
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
Ad

Recently uploaded (20)

dynastic art of the Pallava dynasty south India
dynastic art of the Pallava dynasty south Indiadynastic art of the Pallava dynasty south India
dynastic art of the Pallava dynasty south India
PrachiSontakke5
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
Grade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable WorksheetGrade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable Worksheet
Sritoma Majumder
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
Nguyen Thanh Tu Collection
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFAExercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Dr. Nasir Mustafa
 
Contact Lens:::: An Overview.pptx.: Optometry
Contact Lens:::: An Overview.pptx.: OptometryContact Lens:::: An Overview.pptx.: Optometry
Contact Lens:::: An Overview.pptx.: Optometry
MushahidRaza8
 
Real GitHub Copilot Exam Dumps for Success
Real GitHub Copilot Exam Dumps for SuccessReal GitHub Copilot Exam Dumps for Success
Real GitHub Copilot Exam Dumps for Success
Mark Soia
 
"Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules""Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules"
rupalinirmalbpharm
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx   quiz by Ridip HazarikaTHE STG QUIZ GROUP D.pptx   quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
Ridip Hazarika
 
Engage Donors Through Powerful Storytelling.pdf
Engage Donors Through Powerful Storytelling.pdfEngage Donors Through Powerful Storytelling.pdf
Engage Donors Through Powerful Storytelling.pdf
TechSoup
 
Kenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 CohortKenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 Cohort
EducationNC
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
dynastic art of the Pallava dynasty south India
dynastic art of the Pallava dynasty south Indiadynastic art of the Pallava dynasty south India
dynastic art of the Pallava dynasty south India
PrachiSontakke5
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Grade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable WorksheetGrade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable Worksheet
Sritoma Majumder
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
Nguyen Thanh Tu Collection
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFAExercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Dr. Nasir Mustafa
 
Contact Lens:::: An Overview.pptx.: Optometry
Contact Lens:::: An Overview.pptx.: OptometryContact Lens:::: An Overview.pptx.: Optometry
Contact Lens:::: An Overview.pptx.: Optometry
MushahidRaza8
 
Real GitHub Copilot Exam Dumps for Success
Real GitHub Copilot Exam Dumps for SuccessReal GitHub Copilot Exam Dumps for Success
Real GitHub Copilot Exam Dumps for Success
Mark Soia
 
"Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules""Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules"
rupalinirmalbpharm
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx   quiz by Ridip HazarikaTHE STG QUIZ GROUP D.pptx   quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
Ridip Hazarika
 
Engage Donors Through Powerful Storytelling.pdf
Engage Donors Through Powerful Storytelling.pdfEngage Donors Through Powerful Storytelling.pdf
Engage Donors Through Powerful Storytelling.pdf
TechSoup
 
Kenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 CohortKenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 Cohort
EducationNC
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 

Object Oriented Programming using C++ - Part 4

  • 1. OOPS THROUGH C++ 1 Dr. Chandra Sekhar Sanaboina Assistant Professor Department of Computer Science and Engineering University College of Engineering Kakinada Jawaharlal Nehru Technological University Kakinada Website: https://drcs.info Youtube Link: https://www.youtube.com/watch?v=nPjHraTbPeY&list=PLT1ngltOnlJiHbzVvjkU8VzQt9oam8ji4
  • 2. UNIT – IV POINTERS & BINDING POLYMORPHISMS AND VIRTUAL FUNCTIONS 2
  • 3. AGENDA • Pointer • Features of Pointers • Pointer Declaration • Pointer to Class • Pointer Object • The this Pointer • Pointer to Derived Classes and Base Class • Binding Polymorphisms and Virtual Functions • Introduction • Binding in C++ • Virtual Functions • Rules for Virtual Function • Virtual Destructor 3
  • 5. POINTERS • Introduction: • Every variable has a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator which denotes an address in memory • A pointer is a variable whose value is the address of another variable • Like any variable or constant, you must declare a pointer before you can work with it • Syntax: • type *variable_name; • type is the pointer's base type it must be a valid C++ type • var-name is the name of the pointer variable • Benefits: • Some C++ tasks are performed more easily with pointers • Some tasks, such as dynamic memory allocation cannot be performed without them • More than one variable can be modified and returned by function using pointers. • Pointers help in simplifying the complexity of the program. • Pointers increase the execution speed. 5
  • 6. FEATURES OF POINTERS • Pointers save memory space • Allocates memory as and when required • Execution time with pointers is faster • because data are manipulated with the address, that is, direct access to memory location • Memory is accessed efficiently with the pointers • The pointer assigns and releases the memory as well. Hence it can be said the Memory of pointers is dynamically allocated • Pointers are used with data structures. They are useful for representing two-dimensional and multi- dimensional arrays • An array, of any type can be accessed with the help of pointers, without considering its subscript range • Pointers are used for file handling • Pointers are used to allocate memory dynamically • In C++, a pointer declared to a base class could access the object of a derived class. However, a pointer to a derived class cannot access the object of a base class 6
  • 7. USES OF POINTERS • To pass arguments by reference • For accessing array elements • To return multiple values • Dynamic memory allocation • To implement data structures • To do system level programming where memory addresses are useful 7
  • 8. POINTERS CONTD… • int *ip; // pointer to an integer • double *dp; // pointer to a double • float *fp; // pointer to a float • char *ch // pointer to character • Note: The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to 8
  • 9. ADDRESSES IN C++ • When we create a variable in our C++ program, it is assigned some space in the computer memory • The value of this variable is stored in the assigned location • To know the location in the computer memory where the data is stored, C++ provides the & (reference) operator • The operator returns the address that a variable occupies • Example: I • If x is a variable, &x returns the address of the variable 9
  • 10. REFERENCE OPERATOR (&) AND DEFERENCE OPERATOR (*) • The reference operator (&) returns the variable's address • The dereference operator (*) helps us get the value that has been stored in a memory address • Example: • If we have a variable given the name num, stored in the address 0x234 and storing the value 27. • The reference operator (&) will return 0x234. • The dereference operator (*) will return 27. 10
  • 11. POINTERS PROGRAMMING 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; } 11
  • 13. NULL POINTER • If there is no exact address that is to be assigned, then the pointer variable can be assigned a NULL • It should be done during the declaration • Such a pointer is known as a NULL pointer • Its value is zero and is defined in many standard libraries like iostream • Example: #include <iostream> using namespace std; int main() { int *ip = NULL; cout << "Value of ip is: " << ip; return 0; } 13
  • 15. POINTER TO CLASS • A class pointer is a pointer variable that stores address of an object of a class • A pointer to a C++ class is done exactly the same way as a pointer to a structure • To access members of a pointer to a class we use the member access operator -> operator, just as we do with pointers to structures • As with all pointers, you must initialize the pointer before using it 15
  • 16. POINTER TO CLASS CONTD… 16
  • 17. POINTER TO CLASS EXAMPLE #include <iostream> using namespace std; class Box { public: Box(double l = 2.0, double b = 2.0, double h = 2.0) { cout <<"Constructor called." << endl; length = l; breadth = b; height = h; } double Volume() { return length * breadth * height; } private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; int main(void) { Box Box1(3.3, 1.2, 1.5); // Declare box1 Box Box2(8.5, 6.0, 2.0); // Declare box2 Box *ptrBox; // Declare pointer to a class. ptrBox = &Box1; cout << "Volume of Box1: " << ptrBox->Volume() << endl; ptrBox = &Box2; cout << "Volume of Box2: " << ptrBox->Volume() << endl; return 0; } 17
  • 19. POINTERS TO OBJECTS – THIS POINTER • A Variable that holds the address is called a Pointer variable or simply pointer • Similarly, Objects can also have an address, so there is also a pointer that can point to the address of an Object • That Pointer is Known as this Pointer 19
  • 20. THIS POINTER • Every object in C++ has access to its own address through an important pointer called this pointer • The this pointer is an implicit parameter to all member functions. Therefore, inside a member function, this may be used to refer to the invoking object • Friend functions do not have a this pointer, because friends are not members of a class • Only member functions have a this pointer 20
  • 21. THIS POINTER CONTD… • this is a keyword that refers to the current instance of the class • 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 • There can be 3 main usage of this keyword in C++ • It can be used to pass current object as a parameter to another method • It can be used to refer current class instance variable • It can be used to implement chained function calls in C++ 21
  • 22. THIS POINTER EXAMPLE #include <iostream> using namespace std; class Employee { public: int id; string name; float salary; Employee(int id, string name, float sala ry) { this->id = id; this->name = name; this->salary = salary; } void display() { cout<<id<<" "<<name<<" "<<sal ary<<endl; } }; int main(void) { Employee e1 =Employee(101, "Sonoo", 89 0000); //creating an object of Employee Employee e2=Employee(102, "Nakul", 590 00); //creating an object of Employee e1.display(); e2.display(); return 0; } 22
  • 23. THIS POINTER EXAMPLE #include <iostream> using namespace std; class Box { public: Box(double l = 2.0, double b = 2.0, double h = 2.0) { cout <<"Constructor called." << endl; length = l; breadth = b; height = h; } double Volume() { return length * breadth * height; } int compare(Box box) { return this->Volume() > box.Volume(); } private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; int main(void) { Box Box1(3.3, 1.2, 1.5); // Declare box1 Box Box2(8.5, 6.0, 2.0); // Declare box2 if(Box1.compare(Box2)) { cout << "Box2 is smaller than Box1" <<endl; } else { cout << "Box2 is equal to or larger than Box1" <<endl; } return 0; } 23
  • 25. CHAINED FUNCTION CALLS • When a reference to a local object is returned, the returned reference can be used to chain function calls on a single object Test& Test::func () { // Some processing return *this; } 25
  • 26. CHAINED FUNCTION CALLS EXAMPLE #include<iostream> using namespace std; class Test { private: int x; int y; public: Test(int x = 0, int y = 0) { this->x = x; this->y = y; } Test &setX(int a) { x = a; return *this; } Test &setY(int b) { y = b; return *this; } void print() { cout << "x = " << x << " y = " << y << endl; } }; int main() { Test obj1(5, 5); // Chained function calls. All calls modify the same object // as the same object is returned by reference obj1.setX(10).setY(20); obj1.print(); return 0; } 26
  • 28. SMART POINTERS • Problem with Normal Pointers: • Every time we make use of Dynamic Memory Allocation it will create an object for each and every object we create, but not it’s deleting. • When these pointers are not deleted it will lead to leakage of memory from the heap memory • So slowly the entire heap memory may become unused because it’s infinite. So at one stage because of a lack of heap memory, the program will crash 28
  • 29. SMART POINTERS CONTD… • What are Smart Pointers? • The problem with heap memory is that when you don’t need it you must deallocate • So mostly the programmers are too lazy in writing the code for deallocation of objects and that causes severe problem like memory leak which will cause the program to crash • The languages like Java, C#, .Net Framework they provide a garbage collection mechanism to deallocate the object which is not in use • In C++ 11, it introduces smart pointers that automatically manage memory and they will deallocate the object when they are not in use when the pointer is going out of scope automatically it’ll deallocate the memory 29
  • 30. SMART POINTERS CONTD… • Using Smart Pointers, we can make pointers to work in a way that we don’t need to explicitly call delete • A smart pointer is a wrapper class over a pointer with an operator like * and -> overloaded • The objects of smart pointer class look like a pointer but can do many things that a normal pointer can’t like automatic destruction • The idea is to take a class with a pointer, destructor and overloaded operators like * and -> • Since the destructor is automatically called when an object goes out of scope, the dynamically allocated memory would automatically be deleted 30
  • 31. SMART POINTERS CONTD… #include <iostream> using namespace std; class SmartPtr { int* ptr; public: explicit SmartPtr(int* p = NULL) { ptr = p; } // Destructor ~SmartPtr() { delete (ptr); } // Overloading dereferencing operator int& operator*() { return *ptr; } }; int main() { SmartPtr ptr(new int()); *ptr = 20; cout << *ptr; // We don't need to call delete ptr: when the object ptr goes out of scope, the destructor for it is automatically called and destructor does delete ptr return 0; } 31
  • 33. BINDING • Introduction • The binding means the process of converting identifiers into addresses • For each variables and functions this binding is done • For functions it is matching the call with the right function definition by the compiler • The binding is done either at compile time or at runtime 33
  • 35. BINDING CONTD… • Types of Binding in C++ • Early Binding • Late Binding 35
  • 37. EARLY BINDING • Early Binding • This is compile time polymorphism • It is also known as Static Binding or Compile-time Binding • The compiler/linker directly associates an address to the function call • Function overloading it is an example of early binding • Function overriding in which the base and derived classes have functions with the same name, parameters and return type is also an example of early binding • It is the default binding process in C++ 37
  • 38. EARLY BINDING EXAMPLE #include<iostream> using namespace std; class Base { public: void display() { cout<<" In Base class" <<endl; } }; class Derived: public Base { public: void display() { cout<<"In Derived class" << endl; } }; int main(void) { Base *base_pointer = new Derived; base_pointer->display(); return 0; } 38
  • 39. EARLY BINDING EXAMPLE 2 #include <iostream> using namespace std; class Animals { public: void sound() { cout << "This is parent class" << endl; } }; class Dogs : public Animals { public: void sound() { cout << "Dogs bark" << endl; } }; int main() { Animals *a; Dogs d; a= &d; a -> sound(); // early binding return 0; } 39
  • 41. LATE BINDING • Late Binding • This is run time polymorphism • It is also known as Dynamic Binding or Runtime Binding • In this type of binding the compiler adds code that identifies the object type at runtime then matches the call with the right function definition • This is achieved by using virtual function 41
  • 43. VIRTUAL FUNCTION • A C++ virtual function is a member function in the base class that you redefine in a derived class • It is declared using the virtual keyword • A 'virtual' is a keyword preceding the normal declaration of a function. • It is used to tell the compiler to perform dynamic linkage or late binding on the function • There is a necessity to use the single pointer to refer to all the objects of the different classes. So, we create the pointer to the base class that refers to all the derived objects. But, when base class pointer contains the address of the derived class object, always executes the base class function. This issue can only be resolved by using the 'virtual' function. • When the function is made virtual, C++ determines which function is to be invoked at the runtime based on the type of the object pointed by the base class pointer 43
  • 44. RULES FOR VIRTUAL FUNCTION • Virtual functions must be members of some class • Virtual functions cannot be static members • They are accessed through object pointers • They can be a friend of another class • A virtual function must be defined in the base class, even though it is not used • The prototypes of a virtual function of the base class and all the derived classes must be identical. If the two functions with the same name but different prototypes, C++ will consider them as the overloaded functions • We cannot have a virtual constructor, but we can have a virtual destructor 44
  • 45. LATE BINDING EXAMPLE #include<iostream> using namespace std; class Base { public: virtual void display() { cout<<"In Base class" << endl; } }; class Derived: public Base { public: void display() { cout<<"In Derived class" <<endl; } }; int main() { Base *base_pointer = new Derived; base_pointer->display(); return 0; } 45
  • 46. LATE BINDING EXAMPLE 2 #include <iostream> using namespace std; class Animals { public: virtual void sound() { cout << "This is parent class" << endl; } }; class Dogs : public Animals { public: void sound() { cout << "Dogs bark" << endl; } }; int main() { Animals *a; Dogs d; a= &d; a -> sound(); return 0; } 46
  • 47. LATE BINDING CONTD… • We can also call private function of derived class from a base class pointer by declaring that function in the base class as virtual • Compiler checks if the members of a class are private, public or protected only at compile time and not at runtime • Since our function is being called at runtime, so we can call any type of function, private or public 47
  • 48. LATE BINDING EXAMPLE 2 #include <iostream> using namespace std; class Animals { public: virtual void sound() { cout << "This is parent class" << endl; } }; class Dogs : public Animals { private: virtual void sound() { cout << "Dogs bark" << endl; } }; int main() { Animals *a; Dogs b; a = &b; a->sound(); return 0; } 48
  • 50. PURE VIRTUAL FUNCTIONS • Pure virtual function is a virtual function which has no definition • Pure virtual functions are also called abstract functions • To create a pure virtual function, we assign a value 0 • Syntax: • virtual void func_name() = 0; 50
  • 51. PURE VIRTUAL FUNCTIONS CONTD… • A virtual function is not used for performing any task. It only serves as a placeholder • When the function has no definition, such function is known as "do-nothing" function • The "do-nothing" function is known as a pure virtual function. A pure virtual function is a function declared in the base class that has no definition relative to the base class • A class containing the pure virtual function cannot be used to declare the objects of its own, such classes are known as abstract base classes • The main objective of the base class is to provide the traits to the derived classes and to create the base pointer used for achieving the runtime polymorphism 51
  • 53. ABSTRACT CLASS • An abstract class is a class whose instances (objects) can't be made • We can only make objects of its subclass (if they are not abstract) • Abstract class is also known as abstract base class. • An abstract class has at least one abstract function (pure virtual function) 53
  • 54. ABSTRACT CLASS EXAMPLE #include <iostream> using namespace std; class Employee // abstract base class { virtual int getSalary() = 0; // pure virtual function }; class Developer : public Employee { int salary; public: Developer(int s) { salary = s; } int getSalary() { return salary; } }; class Driver : public Employee { int salary; public: Driver(int t) { salary = t; } int getSalary() { return salary; } }; int main() { Developer d1(5000); Driver d2(3000); int a, b; a = d1.getSalary(); b = d2.getSalary(); cout << "Salary of Developer : " << a << endl; cout << "Salary of Driver : " << b << endl; return 0; } 54
  • 55. ABSTRACT CLASS CONTD… • Subclasses of an abstract base class must define the abstract method, otherwise, they will also become abstract classes • In an abstract class, we can also have other functions and variables apart from pure virtual function 55
  • 56. ABSTRACT CLASS EXAMPLE #include <iostream> using namespace std; class Animals { public: virtual void sound() = 0; }; class Dogs : public Animals { public: void sound() { cout << "Dogs bark" << endl; } }; class Cats : public Animals { public: void sound() { cout << "Cats meow" << endl; } }; class Pigs { public: void sound() { cout << "Pigs snort" << endl; } }; int main() { Dogs d; Cats c; Pigs p; d.sound(); c.sound(); p.sound(); return 0; } 56
  • 58. DESTRUCTOR • A destructor in C++ is a member function of a class used to free the space occupied by or delete an object of the class that goes out of scope • A destructor has the same name as the name of the constructor function in a class, but the destructor uses a tilde (~) sign before its function name 58
  • 60. VIRTUAL DESTRUCTOR • A virtual destructor is used to free up the memory space allocated by the derived class object or instance while deleting instances of the derived class using a base class pointer object • A base or parent class destructor use the virtual keyword that ensures both base class and the derived class destructor will be called at run time, but it called the derived class first and then base class to release the space occupied by both destructors 60
  • 61. WHY VIRTUAL DESTRUCTORS • When an object in the class goes out of scope or the execution of the main() function is about to end, a destructor is automatically called into the program to free up the space occupied by the class • When a pointer of the base class is deleted that points to the derived class, only the parent class destructor is called due to the early bind by the compiler • In this way, it skips calling the derived class destructor, which leads to memory leaks issue in the program • When we use virtual keyword preceded by the destructor tilde (~) sign inside the base class, it guarantees that first the derived class destructor is called and then the base class destructor is called to release the space occupied by both destructors in the inheritance class 61
  • 62. WITHOUT VIRTUAL DESTRUCTORS EXAMPLE #include<iostream> using namespace std; class Base { public: Base() // Constructor function. { cout<< "n Constructor Base class"; } ~Base() // Destructor function { cout<< "n Destructor Base class"; } }; Output: Constructor Base Class Constructor Derived Class Destructor Base Class class Derived: public Base { public: Derived() // Constructor function { cout << "n Constructor Derived class" ; } ~Derived() // Destructor function { cout << "n Destructor Derived class" ; } }; int main() { Base *bptr = new Derived; // Create a base class pointer o bject delete bptr; /* Here pointer object is called to delete the space occupied by the destructor.*/ } 62
  • 63. WITH VIRTUAL DESTRUCTORS EXAMPLE #include<iostream> using namespace std; class Base { public: Base() // Constructor member function. { cout << "n Constructor Base class"; // It prints f irst. } virtual ~Base() // Define the virtual destructor func tion to call the Destructor Derived function. { cout << "n Destructor Base class"; / } }; Output: Constructor Base Class Constructor Derived Class Destructor Derived Class Destructor Base Class class Derived: public Base { public: Derived() // Constructor function. { cout << "n Constructor Derived class" ; /* After p rint the Constructor Base, now it will prints. */ } ~Derived() // Destructor function { cout << "n Destructor Derived class"; /* The virt ual Base Class? Destructor calls it before calling the B ase Class Destructor. */ } }; int main() { Base *bptr = new Derived; // A pointer object ref erence the Base class. delete bptr; // Delete the pointer object. } 63
  • 65. PURE VIRTUAL DESTRUCTORS • Pure Virtual Destructors are legal in C++ • Pure virtual Destructors must be defined, which is against the pure virtual behavior • The only difference between Virtual and Pure Virtual Destructor is, that pure virtual destructor will make its Base class Abstract, hence you cannot create object of that class • There is no requirement of implementing pure virtual destructors in the derived classes 65
  • 66. PURE VIRTUAL DESTRUCTOR EXAMPLE class Base { public: virtual ~Base() = 0; // Pure Virtual Destructor }; // Definition of Pure Virtual Destructor Base::~Base() { cout << "Base Destructorn"; } class Derived:public Base { public: ~Derived() { cout<< "Derived Destructor"; } }; int main() { Base* b = new Derived; // Upcasting delete b; } 66