0% found this document useful (0 votes)
67 views23 pages

OOP - Constructors and Destructors

The document discusses different types of constructors in C++ including default, parameterized, copy, dynamic, and dummy constructors. It provides examples of how each constructor is defined and used, explaining that constructors initialize object values after storage allocation and are called automatically whenever a new object is created. Key points covered include constructor overloading, default arguments, memory allocation using new, and initializing data members with passed arguments.

Uploaded by

Shibam Ojha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views23 pages

OOP - Constructors and Destructors

The document discusses different types of constructors in C++ including default, parameterized, copy, dynamic, and dummy constructors. It provides examples of how each constructor is defined and used, explaining that constructors initialize object values after storage allocation and are called automatically whenever a new object is created. Key points covered include constructor overloading, default arguments, memory allocation using new, and initializing data members with passed arguments.

Uploaded by

Shibam Ojha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

OOP (IT-2001)

KALINGA INSTITUTE OF INDUSTRIAL


TECHNOLOGY

School of Computer Engineering

Strictly for internal circulation (within KIIT) and reference only. Not for outside circulation without permission

Lecture Note
3 Credit Mr. Rajat Behera - Associate Professor
Course Contents cont…
2

Sr # Major and Detailed Coverage Area Hrs


4 Constructors and Destructors 3
• Definition of constructors & its uses
• Types of constructors: default constructor,
parameterized constructor, copy constructor,
constructor with dynamic allocation - Dynamic
Constructors
• Constructor Overloading
• Destructors

School of Computer Engineering


Constructor
3

Constructors are special class functions which performs initialization of every object.
The Compiler calls the Constructor whenever an object is created. Constructors initialize
values to object members after storage is allocated to the object. While defining a
constructors, one must remember that the name of constructor will be same as the name
of the class, and constructors never have return type.
Constructor definition inside the class Constructor definition outside the class
class A class A
{ {
int x; int i;
public: public:
A() //Constructor definition A(); //Constructor declaration
{ };
x = 10; A::A() // Constructor definition
} {
}; i=1;
}
School of Computer Engineering
Points to Remember for Constructor
4

 The constructor must be declared in the public section


 A constructor can never return any value
 Constructor should not be explicitly called, it is automatically
invoked when an object of the class is created
 C++ runtime mechanism ensure that constructor is the first
member function to be executed when an object of that class is
created.
 The address of the constructor cannot be referred to in programs.
Therefore, pointers and references don’t work with constructors
 A constructor cannot be declared as static, volatile or const
 Likewise normal function, constructor can also be overloaded
 Likewise normal function, constructor can have default arguments
School of Computer Engineering
Uses of Constructor
5
1. Initialize the data member of the class with some default values.
2. Initialize the data members of the class with arguments passed to the
constructor.
3. Carry out any work when an object is created.
Example
class Product { //Continuation of Program
private : Product(int id, char *str) { //Point 2
int pId; pId = id;
chart pName[100]; strcpy(pName,str);
public: }
Product() {
pId = rand() % 100; // range 0 to 99 and Point 1
doSomeWork(); // Point 3
}
School of Computer Engineering
Constructor Type
6

Copy

Dummy Dynamic
Constructor

Parameterized Default

School of Computer Engineering


Dummy Constructor
7

The C++ run time mechanism calls a dummy constructor which does not perform any
action. The action means, it does not initialize any data members and thus the variable
acquires garbage value.
class set
{ void set :: input(void)
int m, n; {
public: cout << "Input value of m and n"<<"\n";
void input(void); cin >> m>>n;
void display(void); }
}; void set :: display(void)
int main() {
{ cout << m<<n <<"\n";
set a; }
a.display();
return 0;
} School of Computer Engineering
Default Constructor
8

Default constructor is the constructor which doesn't take any argument. It has no
parameter. It simply allocate the storage for the data members of the object. It may
even initializes the values of the data members.
Example
class Cube Note: A default constructor is
{ //continuation of program so important for initialization
int side; int main() of object members, that even if
in the absence of explicit
public: {
constructor definition, the
Cube() Cube c; compiler will provide a
{ cout << c.side; default constructor
side=10; return 0; implicitly.
} }
};

School of Computer Engineering


Parameterized Constructor
9

These are the constructors with parameter. This constructor is used to provide different
values to data members of different objects, by passing the appropriate values as
argument. Example
Constructor with default arguments
class Cube
//continuation of program It is possible to define constructor with
{ default arguments. Example
int main()
public: Complex(float real, float img = 1.5)
{
int side; The default value for img is 1.5. Then
Cube c1 (10);
Cube(int x) the statement complex(5.5) assigns the
Cube c2 (20);
{ value 5.5 to real and 1.5 to img.
Cube c3 (30); However the statement complex(4.5,
side= x;
cout << c1.side; 2.5) assigns 4.5 to real and 2.5 to img.
}
cout << c2.side; Note-
};
cout << c3.side; Cube(int x = 10) i.e. default argument
return 0; constructor is called with either one
argument or no arguments.
}
School of Computer Engineering
Copy Constructor
10

These are special type of Constructors which takes an object as argument, and is used
to copy values of data members of one object into other object. Example
class Cube
{
//continuation of program //continuation of program
public:
int main() cout << c4.side;
int side;
{ return 0;
Cube(Cube & x)
Cube c1 (10); }
{
Note:
side= x.side; Cube c2 (c1);
1. The copy constructor takes
} Cube c3 (30);
a reference to an object of the
Cube(int len) Cube c4 = c3; same class as an argument.
{ cout << c1.side; 2. When more than one
side= len; cout << c2.side; constructor function is
cout << c3.side; defined in a class, the
} constructor is overloaded.
};
School of Computer Engineering
Dynamic Constructor
11

 Dynamic constructor is used to allocate the memory to the objects at the run time.
 Memory is allocated at run time with the help of 'new' operator.
 By using this constructor, we can dynamically initialize the objects

Example
class dyncons dyncons(int v) void main()
{ { {
int * p; p=new int; dyncons o1, o2(9);
public: *p=v; cout<<“Value of object o is:"<<o1.dis();
dyncons() } cout<<"value of object o1 is:"<<o2.dis();
{ int dis() }
p=new int; {
*p=10; return(*p);
} }
};
School of Computer Engineering
Dynamic Constructor Example cont…
12

class Student int main()


{ //continuation of program {
public: Student(int x, char *str) int roll_no;
int rollno; { char *name;
char *name; rollno=x ; cin>> roll_no >> name;
Student(int x) name=new char[strlen(str)+1]; Student a(roll_no, name);
{ strcpy(name, str) cout<<a.rollno<<a.name;
rollno=x; } return 0;
name= new char[1]; }; }
}

School of Computer Engineering


Constructor Overloading
13

Just like other member functions, constructors can also be overloaded. In fact
when you have both default and parameterized constructors defined in your
class you are having Overloaded Constructors, one with no parameter and other
with parameter. You can have any number of Constructors in a class that differ in
parameter list. Example
class Student
//continuation of program //continuation of program
{
Student(int x, char str[30]) int main()
public:
{ {
int rollno;
rollno=x ; Student a(10);
char name[30];
strcpy(name,str) ; Student b(11,"Ram");
Student(int x)
} cout <<a.rollno<<a.name;
{
}; cout<<b.rollno<<b.name;
rollno=x;
return 0;
name="None";
}
}
School of Computer Engineering
Destructors
14

Destructor is a special class function which destroys the object as soon as the
scope of object ends. The destructor is called automatically by the compiler
when the object goes out of scope. The syntax for destructor is same as that
for the constructor, the class name is used for the name of destructor, with a
tilde ~ sign as prefix to it. Example -
class A //continuation of program
{ int main()
A() {
{ A obj1; // Constructor Called
cout << "Constructor called"; int x=1;
} if(x)
~A() {
{ A obj2; // Constructor Called
cout << "Destructor called"; } // Destructor Called for obj2
} } // Destructor called for obj1
}; School of Computer Engineering
Points to Remember for Destructor
15

 The destructor doesn’t return any value


 The destructor doesn’t take any value and hence can’t be
overloaded
 It is declared in public section
 It is called when an object goes out of scope
 The address of the destructor cannot be accessed in the programs
 It can be called from main writing object_name::destructor_name.
E.g. if class is Sample and s is the object of Sample, the destructor
can be called as s::~Sample()
 Destructor can be called from Constructor and Constructor can be
called from the Destructor.

School of Computer Engineering


Dynamic Memory
16

Suppose we want to put a toy in a box, but you only have an approximate
idea of its size. For that, you would require a box whose size is equal to
the approximate size of the toy.
Under-fitting Possible Issues
Over-fitting

Putting a small toy in a Trying to fit a big toy


large box in a smaller box.

Solution?
A Good Fit
School of Computer Engineering
Dynamic Memory Cont…
17

Two Parts of Memory -


 Stack - Memory from the stack is used by all the
members which are declared inside functions.
 Heap - This memory is unused and can be used
to dynamically allocate the memory at runtime.

new operator
The new operator is used to allocate memory at runtime and is allocated in
bytes. To allocate a variable dynamically, syntax is int *ptr = new int;
By writing new int, we allocated the space in memory required by an integer.
Then we assigned the address of that memory to an integer pointer ptr.
We assign value to that memory as *ptr = 4 (for example);
When we dynamically allocate some memory to a variable, we actually use the heap memory.

School of Computer Engineering


Delete operator
18

Suppose we allocated some memory to a


variable dynamically and then we realize
Example
that the variable is not needed anymore #include <iostream>
in the program. In that case, we need to int main()
free the memory which we had assigned {
to that variable. For that, we use the int *ptr = new int;
delete operator. *ptr = 4;
std::cout << *ptr << std::endl;
It is advised to free the dynamically
allocated memory after the program delete ptr;
finishes so that it becomes available for return 0;
future use. }
To delete the memory assigned to a
variable, we simply need to write the
code as delete ptr;
School of Computer Engineering
Dynamic Allocation for Arrays
19

School of Computer Engineering


Dynamic Allocation for Objects
20

Constructor is a member function of a class which is called whenever a new


object is created of that class. It is used to initialize that object. Destructor is also
a class member function which is called whenever the object goes out of scope.
#include <iostream>
using namespace std;
class A
{
int main()
public:
{
A() {
A* a = new A[4];
cout << "Constructor" << endl;
delete [] a; // Delete array
}
return 0;
~A() {
}
cout << "Destructor" << endl;
}
};

School of Computer Engineering


21

School of Computer Engineering


Home Work (HW)
22

1. Define a class called Point that stores the x and y coordinates of the point. WAP
that uses parameterized constructor for initializing the class objects and also
display the coordinates.
2. Define a class called Complex that stores real and imaginary part of the
complex number. WAP that uses overloaded constructors for initializing the
class objects and also display the part.
3. WAP using appropriate constructors and destructors to represent the bank
account with following specification
 Private members
 Name of the depositor  Type of account
 Account number  Balance amount in the account
 Public members function to
 Assign initial values  Withdraw an amount after checking balance
 Deposit an amount  Display name and balance

School of Computer Engineering


Home Work (HW)
23

4. WAP using appropriate constructors and destructors to represent the vector


and include the member functions to form the following tasks:
 Create the vector
 Modify the value of a given element
 Multiply by scalar value
 Display the vector in the form (10, 20, 30,…)
5. A book shop maintains the inventory of books that are being sold at the
workshop. The list includes details such as author, title, price, publisher and
stock position. Whenever a customer wants a book, the sales person inputs the
title and author and the system searches the list and displays whether it is
available or not. If it is not, an appropriate message is displayed. If it is, then the
system displays the book details and requests for the number of copies
required. If the requested copies are available, the total cost of the requested
copies is displayed otherwise the message “Required copies not in stock” is
displayed. WAP using a class called Books with suitable member functions and
constructors.
School of Computer Engineering

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy