SlideShare uma empresa Scribd logo
1 de 67
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

Pointers in c language
Pointers in c languagePointers in c language
Pointers in c languageTanmay Modi
 
Templates in C++
Templates in C++Templates in C++
Templates in C++Tech_MX
 
Looping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonLooping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonPriyankaC44
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception HandlingMegha V
 
Generic programming and concepts that should be in C++
Generic programming and concepts that should be in C++Generic programming and concepts that should be in C++
Generic programming and concepts that should be in C++Anton Kolotaev
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++LPU
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaEdureka!
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in pythonTMARAGATHAM
 

Mais procurados (20)

Python ppt
Python pptPython ppt
Python ppt
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
 
Pointers in c language
Pointers in c languagePointers in c language
Pointers in c language
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Looping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonLooping Statements and Control Statements in Python
Looping Statements and Control Statements in Python
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception Handling
 
Generic programming and concepts that should be in C++
Generic programming and concepts that should be in C++Generic programming and concepts that should be in C++
Generic programming and concepts that should be in C++
 
Python recursion
Python recursionPython recursion
Python recursion
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Python Programming
Python ProgrammingPython Programming
Python Programming
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
 
Java arrays
Java arraysJava arrays
Java arrays
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
 
Strings
StringsStrings
Strings
 
functions of C++
functions of C++functions of C++
functions of C++
 
Pointer in C++
Pointer in C++Pointer in C++
Pointer in C++
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 

Semelhante a Object Oriented Programming using C++ - Part 4

FUNCTIONS, CLASSES AND OBJECTS.pptx
FUNCTIONS, CLASSES AND OBJECTS.pptxFUNCTIONS, CLASSES AND OBJECTS.pptx
FUNCTIONS, CLASSES AND OBJECTS.pptxDeepasCSE
 
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxCONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxDeepasCSE
 
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 OtherBlue Elephant Consulting
 
C# 7 development
C# 7 developmentC# 7 development
C# 7 developmentFisnik Doko
 
Nitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptxNitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptxshivam460694
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overviewTAlha MAlik
 
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 explainedhozaifafadl
 
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 operatorSAFFI 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.pptxsangeeta borde
 
Arrry structure Stacks in data structure
Arrry structure Stacks  in data structureArrry structure Stacks  in data structure
Arrry structure Stacks in data structurelodhran-hayat
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++Manzoor ALam
 
pointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismpointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismrattaj
 
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays 2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays kinan keshkeh
 

Semelhante a Object Oriented Programming using C++ - Part 4 (20)

Lecture2.ppt
Lecture2.pptLecture2.ppt
Lecture2.ppt
 
FUNCTIONS, CLASSES AND OBJECTS.pptx
FUNCTIONS, CLASSES AND OBJECTS.pptxFUNCTIONS, CLASSES AND OBJECTS.pptx
FUNCTIONS, CLASSES AND OBJECTS.pptx
 
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxCONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
 
Chp3(pointers ref)
Chp3(pointers ref)Chp3(pointers ref)
Chp3(pointers ref)
 
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
 
C# 7 development
C# 7 developmentC# 7 development
C# 7 development
 
C
CC
C
 
Nitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptxNitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptx
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
 
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
 
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
 
C++_notes.pdf
C++_notes.pdfC++_notes.pdf
C++_notes.pdf
 
c++ UNIT II.pptx
c++ UNIT II.pptxc++ UNIT II.pptx
c++ UNIT II.pptx
 
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
 
Arrry structure Stacks in data structure
Arrry structure Stacks  in data structureArrry structure Stacks  in data structure
Arrry structure Stacks in data structure
 
Chp4(ref dynamic)
Chp4(ref dynamic)Chp4(ref dynamic)
Chp4(ref dynamic)
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
 
pointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismpointers,virtual functions and polymorphism
pointers,virtual functions and polymorphism
 
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays 2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
 

Último

Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 

Último (20)

Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 

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