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
View study notes of Function overloading .you can also visit Tutorialfocus.net to get complete description step wise of the concerned topic.Other topics and notes of C++ are also explained.
This Presentation gives you all knowledge about #CPointers, #PointersInC.
The given slides are as follows:
1. Introduction of Pointers.
2. Systems to create a pointer in C.
3. Valid Pointer Examples in C.
4. Graphical representation of address assigning in c using pointer.
5. 1st Sample program of pointers in C.
6. Types of Pointers
7. NULL Pointer in C (Types of Pointer)
8. void Pointer in C (Types of Pointer)
9. Wild Pointer in C (Types of Pointer)
10. Changing value of variable using pointer
11. Update and Access value of variable using pointer in example.
12. Types of format specifies to print address in different format.
13. Advantages of Pointer in C.
14. Disadvantages of Pointer in C.
15. Pointers with Array using Programs. #pointerwitharray
16. Another Example of #pointerwitharray.
17. Relationship Between Arrays and Pointers.
18. Relationship Between Arrays and Pointers explanation with diagram.
19. Pointers and String. #PointersAndString
20. Function with Array Parameters using pointers.
21. Passing Pointers to Function or Pointer argument function. #PointerWithFunction
Our trainer’s having vast experience in real time environment. If anyone has a dream for their career in software programming, then go for java because it is a popular route to establish and fulfill your dreams.
We offer the best quality and affordable training, so you get trained from where you are, from our experienced instructors, remotely using Webex / Gotomeeting.
Pointers are among C’s most powerful, yet most difficult concepts to master. Some tasks like dynamic memory allocation done only by using pointers. So it is essential to learn pointers.
Pointers are a type of variable, just like int, double, etc., except instead of storing a value, they store a memory address of another variable.
Functions, classes, and objects are fundamental concepts in object-oriented programming. Here's a brief explanation of each:
Functions:
Functions are blocks of code that perform specific tasks or computations.
They encapsulate a set of instructions and can take parameters (input) and return values (output).
Functions are reusable, promoting code modularity and maintainability.
Classes:
Classes are blueprints or templates for creating objects.
They define the structure and behavior of objects by specifying attributes (data members) and methods (functions) that the objects will have.
Classes serve as a model for creating multiple instances (objects) with similar characteristics.
Objects:
Objects are instances of classes.
They are concrete representations of the class's blueprint, with their own unique data values and the ability to perform actions using the methods defined in the class.
Objects are used to model and manipulate real-world entities in code.
In summary, functions are used to define specific tasks or operations, classes serve as templates for creating objects with shared attributes and behaviors, and objects are instances of classes that represent real-world entities and can interact with their environment. These concepts are central to object-oriented programming and software development.
View study notes of Function overloading .you can also visit Tutorialfocus.net to get complete description step wise of the concerned topic.Other topics and notes of C++ are also explained.
This Presentation gives you all knowledge about #CPointers, #PointersInC.
The given slides are as follows:
1. Introduction of Pointers.
2. Systems to create a pointer in C.
3. Valid Pointer Examples in C.
4. Graphical representation of address assigning in c using pointer.
5. 1st Sample program of pointers in C.
6. Types of Pointers
7. NULL Pointer in C (Types of Pointer)
8. void Pointer in C (Types of Pointer)
9. Wild Pointer in C (Types of Pointer)
10. Changing value of variable using pointer
11. Update and Access value of variable using pointer in example.
12. Types of format specifies to print address in different format.
13. Advantages of Pointer in C.
14. Disadvantages of Pointer in C.
15. Pointers with Array using Programs. #pointerwitharray
16. Another Example of #pointerwitharray.
17. Relationship Between Arrays and Pointers.
18. Relationship Between Arrays and Pointers explanation with diagram.
19. Pointers and String. #PointersAndString
20. Function with Array Parameters using pointers.
21. Passing Pointers to Function or Pointer argument function. #PointerWithFunction
Our trainer’s having vast experience in real time environment. If anyone has a dream for their career in software programming, then go for java because it is a popular route to establish and fulfill your dreams.
We offer the best quality and affordable training, so you get trained from where you are, from our experienced instructors, remotely using Webex / Gotomeeting.
Pointers are among C’s most powerful, yet most difficult concepts to master. Some tasks like dynamic memory allocation done only by using pointers. So it is essential to learn pointers.
Pointers are a type of variable, just like int, double, etc., except instead of storing a value, they store a memory address of another variable.
Functions, classes, and objects are fundamental concepts in object-oriented programming. Here's a brief explanation of each:
Functions:
Functions are blocks of code that perform specific tasks or computations.
They encapsulate a set of instructions and can take parameters (input) and return values (output).
Functions are reusable, promoting code modularity and maintainability.
Classes:
Classes are blueprints or templates for creating objects.
They define the structure and behavior of objects by specifying attributes (data members) and methods (functions) that the objects will have.
Classes serve as a model for creating multiple instances (objects) with similar characteristics.
Objects:
Objects are instances of classes.
They are concrete representations of the class's blueprint, with their own unique data values and the ability to perform actions using the methods defined in the class.
Objects are used to model and manipulate real-world entities in code.
In summary, functions are used to define specific tasks or operations, classes serve as templates for creating objects with shared attributes and behaviors, and objects are instances of classes that represent real-world entities and can interact with their environment. These concepts are central to object-oriented programming and software development.
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxDeepasCSE
Certainly, here's a brief explanation of constructors, destructors, and operator overloading without using code:
Constructors: Constructors are special methods used to initialize objects of a class. They set the initial state of an object when it is created.
Destructors: Destructors are special methods used to clean up resources and perform necessary cleanup when an object is no longer needed or goes out of scope. They ensure proper resource management.
Operator Overloading: Operator overloading is a feature that allows you to define custom behaviors for operators such as +, -, *, /, etc., when they are applied to objects of your class. It enables you to work with objects in a way that is meaningful for your specific class.
Constructors can be of different types:
Default Constructors: Initialize objects with default values.
Parameterized Constructors: Accept arguments to initialize objects with specific values.
Copy Constructors: Create a new object as a copy of an existing object.
Constructor Overloading: A class can have multiple constructors with different parameter lists, providing flexibility in object initialization.
Destructors are executed automatically when an object is destroyed. They are essential for releasing resources like memory, file handles, or network connections, ensuring proper cleanup and preventing resource leaks.
Operator overloading enables you to define how operators work with objects of your class. For instance, you can specify what the + operator does when applied to two objects of your class, allowing for custom operations that make sense in the context of your class's functionality.
In summary, constructors initialize objects, destructors handle cleanup, and operator overloading allows custom operations with operators when working with objects. These features are crucial for building custom classes in object-oriented programming.
This presentation is a part of the COP2272C college level course taught at the Florida Polytechnic University located in Lakeland Florida. The purpose of this course is to introduce students to the C++ language and the fundamentals of object orientated programming..
The course is one semester in length and meets for 2 hours twice a week. The Instructor is Dr. Jim Anderson.
Ethnobotany and Ethnopharmacology:
Ethnobotany in herbal drug evaluation,
Impact of Ethnobotany in traditional medicine,
New development in herbals,
Bio-prospecting tools for drug discovery,
Role of Ethnopharmacology in drug evaluation,
Reverse Pharmacology.
Synthetic Fiber Construction in lab .pptxPavel ( NSTU)
Synthetic fiber production is a fascinating and complex field that blends chemistry, engineering, and environmental science. By understanding these aspects, students can gain a comprehensive view of synthetic fiber production, its impact on society and the environment, and the potential for future innovations. Synthetic fibers play a crucial role in modern society, impacting various aspects of daily life, industry, and the environment. ynthetic fibers are integral to modern life, offering a range of benefits from cost-effectiveness and versatility to innovative applications and performance characteristics. While they pose environmental challenges, ongoing research and development aim to create more sustainable and eco-friendly alternatives. Understanding the importance of synthetic fibers helps in appreciating their role in the economy, industry, and daily life, while also emphasizing the need for sustainable practices and innovation.
This is a presentation by Dada Robert in a Your Skill Boost masterclass organised by the Excellence Foundation for South Sudan (EFSS) on Saturday, the 25th and Sunday, the 26th of May 2024.
He discussed the concept of quality improvement, emphasizing its applicability to various aspects of life, including personal, project, and program improvements. He defined quality as doing the right thing at the right time in the right way to achieve the best possible results and discussed the concept of the "gap" between what we know and what we do, and how this gap represents the areas we need to improve. He explained the scientific approach to quality improvement, which involves systematic performance analysis, testing and learning, and implementing change ideas. He also highlighted the importance of client focus and a team approach to quality improvement.
Palestine last event orientationfvgnh .pptxRaedMohamed3
An EFL lesson about the current events in Palestine. It is intended to be for intermediate students who wish to increase their listening skills through a short lesson in power point.
Read| The latest issue of The Challenger is here! We are thrilled to announce that our school paper has qualified for the NATIONAL SCHOOLS PRESS CONFERENCE (NSPC) 2024. Thank you for your unwavering support and trust. Dive into the stories that made us stand out!
How to Create Map Views in the Odoo 17 ERPCeline George
The map views are useful for providing a geographical representation of data. They allow users to visualize and analyze the data in a more intuitive manner.
Unit 8 - Information and Communication Technology (Paper I).pdfThiyagu K
This slides describes the basic concepts of ICT, basics of Email, Emerging Technology and Digital Initiatives in Education. This presentations aligns with the UGC Paper I syllabus.
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
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
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
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