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

Dynamic Memory Allocation

Dynamic memory allocation in C/C++ allows programmers to manually allocate and free memory during runtime. Memory is allocated on the heap and can be of variable size, providing flexibility. Programmers are responsible for deallocating memory using operators like new and delete to prevent memory leaks. Common uses include dynamically sized arrays and allocating objects.

Uploaded by

D M
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
79 views

Dynamic Memory Allocation

Dynamic memory allocation in C/C++ allows programmers to manually allocate and free memory during runtime. Memory is allocated on the heap and can be of variable size, providing flexibility. Programmers are responsible for deallocating memory using operators like new and delete to prevent memory leaks. Common uses include dynamically sized arrays and allocating objects.

Uploaded by

D M
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 45

Dynamic Memory Allocation

new and delete operators in C++ for


dynamic memory
Dynamic memory allocation in C/C++ refers to
performing memory allocation manually by
programmer. Dynamically allocated memory is
allocated on Heap and non-static and local
variables get memory allocated on Stack 
• One use of dynamically allocated memory is to
allocate memory of variable size which is not
possible with compiler allocated memory.
• The most important use is flexibility provided
to programmers. We are free to allocate and
deallocate memory whenever we need and
whenever we don’t need anymore. There are
many cases where this flexibility helps. 
How is it different from memory allocated to
normal variables?
For normal variables like “int a”, “char str[10]”,
etc, memory is automatically allocated and
deallocated. For dynamically allocated memory
like “int *p = new int[10]”, it is programmers
responsibility to deallocate memory when no
longer needed. If programmer doesn’t
deallocate memory, it causes memory leak
(memory is not deallocated until program
terminates).
new operator

The new operator denotes a request for memory allocation on


the Free Store. If sufficient memory is available, new operator
initializes the memory and returns the address of the newly
allocated and initialized memory to the pointer variable. 
Syntax:
• Syntax to use new operator: To allocate memory of any data
type, the syntax is:
pointer-variable = new data-type;
// Pointer initialized with NULL
// Then request memory for the variable
int *p = NULL;
p = new int;

OR

// Combine declaration of pointer


// and their assignment
int *p = new int;
Allocate block of memory: new operator is also used to allocate
a block(an array) of memory of type data-type.

pointer-variable = new data-type[size];


where size(a variable) specifies the number of elements in an
array.
Example:
int *p = new int[10]
Dynamically allocates memory for 10 integers continuously of
type int and returns pointer to the first element of the sequence,
which is assigned to p(a pointer). p[0] refers to first element, p[1]
refers to second element and so on.
Example 1:
#include <iostream>
using namespace std;
int main()
{
int *a,i,n;
cout<<"Enter number of elements\n";
cin>>n;
a=new int[n];
cout<<"Enter elements of array\n";
for(i=0;i<=n-1;i++)
cin>>a[i];
cout<<"Array is ";
for(i=0;i<=n-1;i++)
cout<<a[i]<<" ";

}
Example 2: Allocating memory to ‘n’ number
objects: Dynamic object
#include <iostream> int main()
using namespace std;
class student
{
{ student *s;
int roll_no;
int i,n;
string name;
public: cout<<"enter the number of
void get() students\n";
{ cin>>n;
cout<<"Enter roll_no and name\n";
cin>>roll_no; s=new student[n];
fflush(stdin); for(i=0;i<=n-i;i++)
getline(cin,name);
s[i].get();
}
void show() for(i=0;i<=n-i;i++)
{ s[i].show();
cout<<endl<<roll_no<<" "<<name;
}
}; }
MCQ 1
• In CPP, dynamic memory allocation is done
using ______________ operator.
a. calloc()
b. malloc()
c. allocate
d. New
• Which of the following is/are valid ways to
allocate memory for an integer by dynamic
memory allocation in CPP?

a. int *p = new int(100);


b. int *p; p = new int; *p = 100;
c. int *p = NULL; p = new int; *p=100;
d. All of these
•  During dynamic memory allocation in CPP,
new operator returns _________ value if
memory allocation is unsuccessful.
a. False
b. NULL
c. Zero
d. None of these
Delete operator
delete operator

Since it is programmer’s responsibility to deallocate dynamically


allocated memory, programmers are provided delete operator by
C++ language.

Syntax:
delete pointer_variable
Or
delete [] pointer_variable
• Can we allocate memory for the objects
dynamically in CPP?
Yes
 No
The correct syntax of new operator is:
a. data_type * var= new data_type(value);
b. data_type * var= new data_type;
c. data_type * var= new data_type[size];
d. All of mentioned above
• Which of the following is true about new when
compared with malloc. 1) new is an operator, malloc is
a function 2) new calls constructor, malloc doesn't 3)
new returns appropriate pointer, malloc returns void *
and pointer needs to typecast to appropriate type.
A. 1 and 3
B. 2 and 3
C. 1 and 2
D. All 1, 2 and 3
Predict the output?
#include <iostream>
using namespace std;

class Test
{
int x;
Test() { x = 5;}
};

int main()
{
Test *t = new Test;
cout << t->x;
}

a. Compiler Error
b. 5
c. 0
d. Garbage Value
• Write a program to declare a class employee
with id, name and salary. Allocate memory to
‘n’ number of employees and write the details
onto file emp.txt and then read the file print
the details.
Virtual Function in C++

A virtual function is a member function which is declared within a


base class and is re-defined (overridden) by a derived class. When
you refer to a derived class object using a pointer or a reference to
the base class, you can call a virtual function for that object and
execute the derived class’s version of the function. 
• Virtual functions ensure that the correct function is called for an
object, regardless of the type of reference (or pointer) used for
function call.
• They are mainly used to achieve Runtime polymorphism
• Functions are declared with a virtual keyword in base class.
• The resolving of function call is done at runtime.
Rules for Virtual Functions

• Virtual functions cannot be static.


• A virtual function can be a friend function of another class.
• Virtual functions should be accessed using pointer or
reference of base class type to achieve runtime
polymorphism.
• The prototype of virtual functions should be the same in the
base as well as derived class.
• They are always defined in the base class and overridden in a
derived class. It is not mandatory for the derived class to
override (or re-define the virtual function), in that case, the
base class version of the function is used.
• A class may have virtual destructor but it cannot have a virtual
constructor.
int main()
#include<iostream> {
using namespace std;
base *bptr;
class base {
public: derived d;
virtual void print()
{ bptr = &d;
cout << "print base class\n";
}

void show()
// Virtual function, binded at
{ runtime
cout << "show base class\n";
} bptr->print();
};

class derived : public base {


public: // Non-virtual function, binded at
void print()
{
compile time
cout << "print derived class\n"; bptr->show();
}

void show()
{ return 0;
cout << "show derived class\n";
} }
};
Explanation
 Runtime polymorphism is achieved only through a pointer (or
reference) of base class type. Also, a base class pointer can point to
the objects of base class as well as to the objects of derived class. In
above code, base class pointer ‘bptr’ contains the address of object
‘d’ of derived class.
Late binding (Runtime) is done in accordance with the content of
pointer (i.e. location pointed to by pointer) and Early binding
(Compile time) is done according to the type of pointer, since print()
function is declared with virtual keyword so it will be bound at
runtime (output is print derived class as pointer is pointing to object
of derived class) and show() is non-virtual so it will be bound during
compile time (output is show base class as pointer is of base type).
Problem on virtual function
• Write a program to declare a class shape with 2 data
member and 1 virtual function area(). Make 2 derived
classes rectangle and triangle which will calculate the area
of triangle and rectangle by overriding area() function.
• Write a program to declare a class person with name and
city as data members. Declare student and teacher class
that inherits from person class to show the details of
respective classes. Assume parameterized constructor in
both the classes. Assume virtual function void show() in
base class person that will be overridden in later inherited
classes.
C++ Function Overriding

As we know, inheritance is a feature of OOP that allows


us to create derived classes from a base class. The
derived classes inherit features of the base class.
Suppose, the same function is defined in both the
derived class and the based class. Now if we call this
function using the object of the derived class, the
function of the derived class is executed.
This is known as function overriding in C++. The
function in derived class overrides the function in base
class.
Example of function overriding
// C++ program to demonstrate class Derived : public Base {
function overriding public:
void print() {
#include <iostream>
cout << "Derived Function" <<
using namespace std; endl;
}
class Base {
};
public:
void print() {
int main() {
cout << "Base Function" << endl;
Derived derived1;
}
}; derived1.print();
return 0;
}
Abstraction in C++

Data abstraction is one of the most essential and important feature of


object oriented programming in C++. Abstraction means displaying
only essential information and hiding the details. Data abstraction
refers to providing only essential information about the data to the
outside world, hiding the background details or implementation.
Consider a real life example of a man driving a car. The man only
knows that pressing the accelerators will increase the speed of car or
applying brakes will stop the car but he does not know about how on
pressing accelerator the speed is actually increasing, he does not
know about the inner mechanism of the car or the implementation of
accelerator, brakes etc in the car. This is what abstraction is.
Abstraction using Classes: We can implement Abstraction in C++
using classes. Class helps us to group data members and
member functions using available access specifiers. A Class can
decide which data member will be visible to outside world and
which is not.
• Members declared as public in a class, can be accessed from
anywhere in the program.
• Members declared as private in a class, can be accessed only
from within the class. They are not allowed to be accessed
from any part of code outside the class
Pure Virtual Functions and Abstract Classes
in C++
Sometimes implementation of all function cannot be provided in
a base class because we don’t know the implementation. Such a
class is called abstract class.
A pure virtual function (or abstract function) in C++ is a virtual
function for which we can have implementation, But we must
override that function in the derived class, otherwise the derived
class will also become abstract class
A pure virtual function is declared by assigning 0 in declaration.
A class containing atleast 1 pure virtual function is an abstract
class.
// An abstract class
class Test
{
// Data members of class
public:
// Pure Virtual Function
virtual void show() = 0;

/* Other members */
};
#include<iostream> // This class inherits from Base and
implements fun()
using namespace std; class Derived: public Base
{
int y;
class Base public:
void fun() { cout << "fun() called"; }
{ };
int x;
int main(void)
public: {
virtual void fun() = 0; Derived d;
d.fun();
int getX() { return x; } return 0;
}; }
Program Example
Write a program to declare a class shape with 2
data member and 1 pure virtual function area().
Make 2 derived classes rectangle and triangle
which will calculate the area of triangle and
rectangle by overriding area() function.
Which among the following best describes polymorphism?

a) It is the ability for a message/data to be processed in more than


one form

b) It is the ability for a message/data to be processed in only 1 form

c) It is the ability for many messages/data to be processed in one


way

d) It is the ability for undefined message/data to be processed in at


least one way
Which is used to create a pure virtual function?
a) $
b) =0
c) &
d) !
• What is an abstract class in C++?
a) Class specifically used as a base class with
atleast one virtual functions
b) Class specifically used as a base class with
atleast one pure virtual functions
c) Class from which any class is derived
d) Any Class in C++ is an abstract class
• Which is the correct syntax of defining a pure
virtual function?
a) pure virtual return_type func();
b) virtual return_type func() pure;
c) virtual return_type func() = 0;
d) virtual return_type func();
Virtual Destructor
Base class destructors should always be virtual. Suppose you use
delete with a base class pointer to a derived class object to
destroy the derived-class object. If the base-class destructor is
not virtual then delete, like a normal member function, calls the
destructor for the base class, not the destructor for the derived
class.
Example of virtual destructor
// Virtual Destructors class B : public A
#include <iostream> {
using namespace std; public:
class A ~B()
{
{
cout<<"Derived class destructor calld\n";
public:
}
virtual ~A()
};
{ int main()
cout<<"Base class destructor called\n";{
} A *a = new B;
delete a;
}; }
Dynamic Constructor in C++
When allocation of memory is done dynamically
using dynamic memory allocator new in a
constructor, it is known as dynamic constructor.
By using this, we can dynamically initialize the
objects.
Example 1
// Dynamic Constructor int main()
#include <iostream> {
using namespace std; A obj;
class A {
char* p;
obj.display();
}
public:
A()
{
// allocating memory at run time /*In this we point data member of type
p = new char[6];
p = "hello";
char which is allocated memory
} dynamically by new operator and when
we create dynamic memory within the
void display() constructor of class this is known as
{
cout << p << endl;
dynamic constructor.*/
}
};
Example 2
#include <iostream>
using namespace std;

class A {
int* p;
public:
A()
{
p = new int[3]{ 1, 2, 3 };
for (int i = 0; i < 3; i++)
{
cout << p[i] << " ";
}
cout << endl;
}
};

int main()
{
A* ptr = new A[5];
}
//In this program we have created array of object dynamically. The first object is ptr[0], second is ptr[1] and so on . For each
object creation default constructor is called and for each object memory is allocated to pointer type variable by new operator.
In the case of friend operator functions how
many object arguments a binary operator
overloaded function can take?
a) 1
b) 2
c) 3
d) 0
Choose the correct sequence of destructors bein
g called for the following code.
class A
{
};
class B
{
};
class C: public A, public B
{
};
a) ~A(), ~B(), ~C()
b) ~B(), ~C(), ~A()
c) ~A(), ~C(), ~B()
d) ~C(), ~B(), ~A()
Destructors can be ________
a) Abstract type
b) Virtual
c) Void
d) Any type depending on situation
Which among the following is correct for the
destructors concept?
a) Destructors can be overloaded
b) Destructors can have only one parameter at
maximum
c) Destructors are always called after object goes
out of scope
d) There can be only one destructor in a class

You might also like