Constructor and
destructor
Ch-2
Constructors
▪ Constructors are class functions that perform initialization of every object.
▪ Constructors initialize values to object members after storage is allocated to
the object.
▪ The Compiler calls the Constructor whenever an object is created.
▪ The name of constructor will be same as the name of the class
▪ Example:
Contd..
▪ Constructors will not have a return type.
▪ Constructors can be defined either inside the class definition or outside class
definition using class name and scope resolution :: operator.
Types of Constructors
▪ The three types of Constructors are:
❑ Default Constructor
❑ Parameterized Constructor
❑ Copy Constructor
Default Constructor
▪ Default constructor does not take any argument. It has no parameter.
▪ Syntax :
Example:
Contd..
▪ After creating the object, the constructor is called which initializes its data
members. A
▪ Default constructor is used for initialization of object members
▪ Even if a constructor is defined explicitly, the compiler will provide a default
constructor implicitly.
Contd..
Characteristics of Constructors
▪ Called automatically when the objects are created.
▪ All objects of the class having a constructor are initialized before using.
▪ Declared in the public section for availability to all the functions.
▪ Default and copy constructors are generated by the compiler wherever
required.
▪ Generated constructors are public.
▪ Can have default arguments like other C++ functions.
▪ A constructor can call member functions of its class.
▪ Return type cannot be specified for constructors.
▪ Constructors cannot be inherited, but a derived class can call the base
class constructor.
▪ Constructors cannot be static.
▪ An object of a class with a constructor cannot be used as a member of a
union.
PARAMETERIZED Example :
CONSTRUCTORS
▪ The constructors possess parameters.
▪ Different values to data members of different
objects can be provided, by passing the
appropriate values as argument.
▪ In the above example, the parameterized
constructor has initialized three objects cb1, cb2
and cb3 with user defined values as 100, 200
and 300 respectively.
Contd..
MULTIPLE CONSTRUCTORS IN CLASS
▪ A class can contain more than one Constructor.
▪ This is called as Constructor Overloading.
▪ All constructors are defined with the same name as that of the class they
belong to.
▪ All constructors can contain different number of arguments.
▪ Based on the number of arguments, the compiler executes the appropriate
constructor.
Contd..
Contd..
Copy constructor
▪ A copy constructor is used to declare and initialize an object from another
object.
▪ Eg: item t2(t1); or item t2=t1;
▪ The process of initializing through a copy constructor is known as copy
initialization.
▪ t2=t1 will not invoke copy constructor.
▪ t1 and t2 are objects, assigns the values of t1 to t2.
▪ A copy constructor takes a reference to an object of the same class as itself as
Contd..
Contd..
DESTRUCTORS
▪ Destructor is a class function that 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.
▪ In the syntax of destructor, the class name is used for the name of
destructor; with a tilde ~ sign as prefix to it.
▪ Destructors will never have any arguments.
Contd..
Characteristics
▪ It does not take any parameter nor does it return any value.
▪ Overloading a destructor is not possible.
▪ A class can have only one destructor. A destructor can be defined outside the
class.
▪ Called automatically when the objects are destroyed.
▪ Destructor functions follow the usual access rules as other member
functions.
▪ De-initializes each object before the object goes out of scope. Cannot be
inherited.
▪ Address of a destructor cannot be taken.
▪ A destructor can call member functions of its class.
▪ An object of a class having a destructor cannot be a member of a union.
Example: Calling Constructor and Destructor
Contd..
▪ Syntax:
Difference between Constructor and Destructor in C++
Constructors Destructors
The constructor initializes the class and allots If the object is no longer required, then
the memory to an object. destructors demolish the objects.
When the object is created, a constructor is When the program gets terminated, the
called automatically. destructor is called automatically.
It receives arguments. It does not receive any argument.
A constructor allows an object to initialize some A destructor allows an object to execute some
of its value before it is used. code at the time of its destruction.
It can be overloaded. It cannot be overloaded.
When it comes to constructors, there can be When it comes to destructors, there is
various constructors in a class. constantly a single destructor in the class.
They are often called in successive order. They are often called in reverse order of
constructor.
Array of objects
▪ We can also have arrays of variables that are type of class. Such variables are
called arrays of objects.
▪ The array of objects are stored inside the memory in the same way as a
multidimensional array.
e.g.
Contd..
Contd..
▪ output
Contd..
Constant objects
▪ In C++, a const object is an instance of a class that has been declared using
the const keyword. This declaration signifies that the object's state,
specifically its data members, cannot be modified after its initial construction.
▪ const objects must be initialized at the time of their declaration, typically
through constructors.
▪ const objects can only call const member functions. A const member function
is one that is guaranteed not to modify the object's state. This restriction
ensures that the immutability of the const object is maintained.
Contd..
Contd..
OPERATOR OVERLOADING
▪ Operator overloading in C++ program can add special features to the functionality and
behavior of already existing operators, such as arithmetic's and other operations.
▪ The mechanism of giving special meaning to an operator is known as operator
overloading. For example, we can overload an operator ‘+’ in a class-like string to
concatenate two strings by just using +.
▪ Operations that can be performed:
▪ Arithmetic operations: + – * / %
▪ Logical operations: && and ||
▪ Relational operations: == != >= <=
▪ Pointer operators: & and *
▪ Memory management operator: new, delete []
Contd..
▪ Operator Overloading provides new function definitions to the normal C++
operators like +, -, *, ++, --, +=,-=, .
▪ The mechanism of providing such an additional definition to an operator is
known as operator overloading in C++.
▪ The overloaded function definitions are for user defined datatypes.
▪ Existing operators alone can be overloaded.
▪ For example, the functionality of „+‟ operator can be extended to strings
through operator overloading instead of using strcat() function.
Contd..
▪ Steps for creating overloaded operators:
▪ a. Create a class that defines the data type for overloading operation.
▪ b. Declare the operator function in the public part of the class
▪ c. Define the operator function for the needed operator.
▪ Operator overloading can be done by implementing a function which can be :
▪ Member Function - Operator overloading function can be a member function if the Left
operand is an Object of that class.
▪ Friend Function - Operator overloading function can be made friend function if it needs
access to the private and protected members of class.
Contd…
▪ The Syntax of declaration of an Operator function is as follows:
▪ Example – declaring an Operator function for „=‟ is, Operator =
Which operators Cannot be overloaded?
▪ Conditional [?:], size of, scope(::), Member selector(.), member pointer selector(.*) and the
casting operators.
▪ We can only overload the operators that exist and cannot create new operators or rename
existing operators.
▪ At least one of the operands in overloaded operators must be user-defined, which means we
cannot overload the minus operator to work with one integer and one double. However, you
could overload the minus operator to work with an integer and a string.
▪ It is not possible to change the number of operands of an operator supports.
▪ All operators keep their default precedence and associations (what they use for), which
cannot be changed.
▪ Only built-in operators can be overloaded.
Rules of operator overloading
▪ Only existing operator can be overloaded
▪ We cannot change the basic meaning of operator.
▪ We cannot change the basic syntax, the grammatical rules that govern its use such
as the number of operands, associativity and precedence.
▪ There are some operators that cannot be overloaded.
▪ Operator overloading is implemented as member function and friend function.
▪ Unary operator takes no argument and does not return value when it is implemented
via member function but takes one argument of type class and can return value.
▪ Binary operators overloaded through member function take one explicit argument
but when overloaded with friend function take two explicit argument.
OVERLOADING UNARY OPERATORS
▪ Unary operator overloading involves ▪ The unary operators that can be
defining behaviors for operators that overloaded are the following:
act on a single operand. ▪ ! (logical NOT)
▪ & (address-of)
▪ Unary operators act on only one
▪ ~ (one's complement)
operand where an operand is simply a
▪ * (pointer dereference)
variable acted on by an operator.
▪ + (unary plus)
There is no restriction on the return
▪ - (unary negation)
types of the unary operators.
▪ ++ (increment)
▪ -- (decrement)
Contd..
▪ The unary operators operate on the object for which they were called and
normally, this operator appears on the left side of the object, as in !obj, -obj,
and ++obj but sometime they can be used as postfix as well like obj++ or obj--
.
▪ Operators can be overloaded for prefix as well as postfix usage.
e.g. overloading unary operator
Contd..
OVERLOADING BINARY OPERATORS
▪ The operator which contains 2 operands is called binary operator overloading
▪ A Binary Operator can be defined either a member function taking one
argument.
▪ An operator function should be either a member or take at least one class
object argument.
▪ An operator function, which needs to accept a basic type as its first
argument, cannot be a member function.
▪ All function work with two operands. The first (Rational) is the operator
overloaded function caller and the second (object) is the passed argument.
▪ The following is the list of binary operators that can be overloaded: !=, && ,
<< , >> etc
e.g. overloading binary operator
Contd..
Contd..
Contd..
Using
friend
function
Contd..
operator overloading for string concatenation
Contd..
Dynamic memory allocation
▪ DMA in C++ allows us to allocate memory to storage components of our program at run-
time. It is one of the most significant features of C++.
▪ C++ Dynamic Memory Allocation is different from that seen in the C. While C uses
functions like malloc(), calloc(), realloc() and free() to handle operations based on DMA,
C++ also uses all the 4 functions in addition to 2 different operators called new and
delete to allocate memory dynamically.
▪ These statements are indicative of the fact that DMA is implemented by the programmer
itself. C++ lacks the feature of a garbage collector which automatically helps to free up
unnecessary memory space occupied by stagnant garbage values.
▪ It is important to note that the memory is dynamically allocated on the Heap. The non-static
memory and local variables get memory allocated on Stack.
Dynamic memory allocation
Significa
Delete
nce of
pointer
DMA
Stack
Memory
and heap
leak
memory
New
operator
Significance of DMA
▪ Dynamic memory allocation is quite different from what the C++ compiler
reserves for variables of fixed length. The implementation of DMA proves to be
pretty flexible for the programmer. The user is free to allocate and deallocate
memory as and when required.
Contd..
▪ Memory map
new Operator in C++
▪ The new operator in C++ indicates a request for memory allocation on the Heap of
the computer memory.
▪ If the Heap has enough memory available in that region, then with the help of
the “new” operator, you can initialize the memory and return the address of the
newly allocated and initialized computer memory to the pointer variable.
Declaration of new Operator
▪ pointer_variable = new data_type;
▪ Another way of using the new keyword is;
▪ data_type *pointer_variable = new data_type;
▪ Here, pointer_variable is a pointer of data_type data-type. It can be of any
built-in or user-defined data types like arrays, structure, and class.
▪ For instance,
▪ int *pointer = NULL;
pointer = new int;
▪ or
▪ int *pointer = new int;
Initialization & allocation of new Operator
▪ The general way of initializing memory dynamically is:
▪ pointer_variable = new data_type(value);
▪ for instance,
▪ int *ipointer = new int(10);
▪ Allocation of new Opewrator
▪ The general way of initializing memory dynamically is:
▪ pointer_variable = new data_type [size];
▪ For instance,
▪ int *pointer = new int [ 5 ]
delete Operator in C++
▪ We use the “delete” operator in C++ for dynamic memory deallocation. Just
like the “new” operator, the “delete” operator is also used by the programmer
to manage computer memory.
▪ Syntax
▪ delete pointer_variable;
▪ For instance,
▪ delete pointer;
Memory Leak in C++
▪ Whenever any mismanagement arises while allocation and deallocation of
memory, memory leaks occur. One of the major drawbacks of C++ is that it
does not have an automatic garbage collector like that seen in Java and
Python. Due to the absence of this feature, memory is not efficiently managed
and hence memory leaks occur. After the use of a pointer, it must be
deallocated by the user manually, otherwise, it would hamper the other tasks
at hand.
e.g.
Dangling Pointer in C++
▪ A pointer that points to the memory address of an object that has already
been deleted is known as a dangling pointer in C++.
▪ This happens when the object is destroyed in the program, that is when we
delete or deallocate an object reference.
Contd..
Questions
▪ Differentiate between static and dynamic memory allocation
▪ Describe memory leak in DMA.
▪ Explain the concept of dangling pointer
Pointer to class object
▪ A pointer to object stores address of object
▪ To create pointer to object the syntax is
▪ classname *pointer_to_object;
▪ To store address of object into pointer to object we use & operator. Syntax is:
▪ pointer_to_object= &objectname;
▪ After storing address of object into pointer to object we can call the member
function using pointer to the object with the help of arrow operator (->).
▪ objectPointer->dataMember; // Accessing a data member
▪ objectPointer->memberFunction(); // Calling a member function
e.g
Pointer to data member
▪ A pointer to data member is used to store the address of a data member of the class.
▪ Pointers to members allow you to refer to nonstatic members of class objects.
▪ You cannot use a pointer to member to point to a static class member because the address of a static member is
not associated with any particular object.
▪ To point to a static class member, you must use a normal pointer.
▪ To declare a pointer to data member we use following syntax:
▪ datatype class_name::*pointer_name;
▪ To assign address of data member of the class we use following syntax:
▪ pointer_name = &class_name::datamember_name;
▪ To use pointer to data member with object we use following syntax:
▪ Object.*pointerToMember
▪ To use pointer to data member with pointer to object we use following syntax:
▪ ObjectPointer->*pointerToMember
e.g
e.g. contd..
Reference to Dynamic Objects
▪ The address of dynamic objects returned by the new operator can be
dereferenced and a reference to them can be created.
▪ Syntax:
▪ ClassName &RefObj = * (new ClassName);
▪ The reference to object RefObj can be used as a normal object. The memory
allocated to such objects cannot be released except during the termination of
the program.
e.g.
Contd..
Live objects
▪ The term "live object" generally refers to an object whose lifetime has begun and is still active and
usable within the program's execution. It implies that the object has been properly constructed
and its resources are available for use.
▪ Or objects created dynamically with their data members initialized during creation are known as
Live Objects.
▪ To create a live object, constructor must be invoked automatically which performs initialization of
data members.
▪ Similarly, the destructor for an object must be invoked automatically before the memory for that
object is deallocated.
▪ A class whose live object is to be crated must have atleast one constructor. The syntax for
▪ Creating a live object is as follows.
▪ Pointer_to_Object = new Class_name(Parameters)
Contd..
▪ Breakdown of what constitutes a "live object" in C++:
▪ Object Lifetime:
▪ An object's lifetime in C++ begins when storage is allocated for it and its constructor (if any) has finished
executing successfully. It ends when its destructor (if any) is called or its storage is released.
▪ Initialization:
▪ A live object has been initialized, either through a default constructor, a user-defined constructor, or by
direct initialization. Accessing an object whose lifetime has begun but has an indeterminate value (i.e.,
not initialized) can lead to undefined behavior.
▪ Accessibility and Usability:
▪ A live object is one that can be accessed and manipulated according to its defined interface (member
functions, public data members). It represents a concrete instance of a class or a fundamental type that
is currently active in memory.
Contd..
Contd..
Pointers to Object Members
(Member Functions)
▪ The general format for defining pointer to member function is as follows
▪ Return_type (Class_name :: * pointer_to_function)(arguments)
▪ To get the address of the member function is as follows
▪ Pointer_to_function = & Class_name :: member_function_name
Pointer to an Object
▪ C++ provides another operator ->* for use exclusively with pointers to
members called member dereferencing operator. This operator is used to
access a member using a pointer to it with pointer to the object.
▪ A pointer to an object is a pointer that can store the memory address of an
object.
▪ The dereferencing operator ->* is used to access the member in case of
pointers to both object and member.
▪ The dereferencing operator .* is used when an object itself accesses the
member pointer.
e.g.
Contd..
Accessing Data Members Through
Object Pointer
▪ Pointer to members in C++ allows you to store and manipulate pointers to
class
▪ We can assign the address(using the &) of a class member (variables or
functions) and assign it to a pointer variable
▪ It is a powerful feature in C++ that enables you to work with class members
in a dynamic and flexible way
▪ A class member pointer can be declared using the operator ::* with the class
name.
Contd..
▪ For example, given a class MyClass
▪ We can define the pointer to a member e.g. data using operator ::* as follows
class MyClass{
private:
int data;
public:
void show();
};
▪ int MyClass ::* ptr=&MyClass :: data;
▪ Here, the statement MyClass ::* ptr is “pointer-to-member” of the class
MyClass.
▪ The statement &MyClass :: data means the address of the member i.e. data of
MyClass.
▪ Let’s say obj is an object of MyClass, we can access the data using the pointer
ptr as follows.
▪ cout<<obj.*ptr;
▪ cout<<[Link]; //It is same as above
Contd..
Dynamic constructor
▪ In C++, a "dynamic constructor" is not a distinct type of constructor with a
specific keyword or syntax. Instead, it refers to the use of a regular class
constructor to perform dynamic memory allocation for the object's data
members at runtime, typically using the new operator.
▪ Example:
▪ A common use case is a class that manages a dynamic array or a string
whose length is not fixed at compile time.
Program
class DynamicArray {
private:
int* arr;
int size;
public:
// Dynamic Constructor
DynamicArray(int s) : size(s) {
arr = new int[size]; // Dynamic memory
allocation
// Initialize array elements (optional)
for (int i = 0; i < size; ++i) {
arr[i] = 0;
}
}
// Destructor to deallocate memory
~DynamicArray() {
delete[] arr;
}
};
TYPE CONVERSION
▪ Implicit conversions are automatically performed when a value is copied to a
compatible type. standard conversion-
▪ Standard conversions affect fundamental data types, and allow the
conversions between numerical types
▪ short to int, int to float double to int to or from bool etc.,
▪ Implicit conversions with classes Implicit conversions can be controlled by
the following member functions:
▪ Single-argument constructors: allow implicit conversion from a particular
type to initialize an object.
▪ Assignment operator: allow implicit conversion from a particular type on
assignments.
Contd..
▪ Type-cast operator: allow implicit conversion to a particular type.
▪ Three types of situations might arise for data conversion between different types :
▪ (i) Conversion from basic type to class type.
▪ (ii) Conversion from class type to basic type.
▪ (iii) Conversion from one class type to another class type.
▪ (i) Basic Type to Class Type
▪ This type of conversion is very easy. If a class object has been used as the left
hand operand
▪ of = operator, the type conversion can also be done by using an overloaded =
operator in
▪ C++.
▪ (ii) Class Type to Basic Type
▪ Define an overloaded casting operator for converting a class type to a basic type.
The syntax
▪ of the conversion function is as follows:
Contd..
▪ The function converts a class type data to typename. For example
▪ o The operator float ( ) converts a class type to type float
▪ o The operator int ( ) converts a class type object to type int.
▪ When a class type to a basic type conversion is required, the compiler will
call the casting
▪ operator function for performing the task.
▪ The following conditions should be satisfied by the casting operator
function :
▪ o It must not have any argument
▪ o It must be a class member
▪ o It must not specify a return type.
Contd..
▪ One Class Type to Another Class Type
▪ During converting one class type data A to another class type data B, A is
referred to as
▪ the Source class and b as Destination class.
▪ The source class performs the conversion and result is given to the object of
destination
▪ class.
▪ The argument of the source class is passed to the destination class for the
purpose of
▪ conversion.
▪ The conversion constructor must be kept in the destination class.
▪ The conversion can be performed in two ways :
▪ (a) Using a constructor.
▪ (b) Using a conversion function.
Thank you