OOP Lec3
OOP Lec3
17-10-2024
Topics covered
Constructors
Destructors
Pointers
Constructors
• A special type of function in programming that is used to create objects.
• Set the initial values or properties of an object when it is created.
• Constructor is called by the compiler whenever the object of the class is created.
• Like functions, a constructor can take arguments that can aid in the initialization.
• Can’t be used to return something like in ordinary functions.
• Mostly, it is accessed publicly.
• Constructors often have the same name as the declaring class.
Constructors
• Used to give an objects some basic functionalities, common to all class object
instances.
• Somewhat similar, to function but used only when new object is "born“.
• It allocates the memory to the object and initializes class data members by
default values or values passed by the user while creating an object.
• There can be many constructors in a class.
• It can be overloaded.
• They are not inherited but called in the child class from the parent class.
Constructors
Methods of defining constructors
::
Scope resolution operator,
represent the relatedness
Output:
Constructors
The four generic types of the constructors.
1. A constructor which does not receive any parameters is called a Default
Constructor or a Zero Argument Constructor.
2. A Parameterized Constructor, can accept one or more arguments.
3. A Copy constructor is used to create a copy of an already existing object of
another class.
4. When the allocation of memory is done dynamically using a dynamic memory
allocator in a new constructor, it is known as a Dynamic constructor.
Destructors
• A Destructor is a member function that is instantaneously called whenever an object is
destroyed.
• The destructor has the same name as the class name, but the name is preceded by a
tilde(~).
• A destructor has no return type and receives no parameters.
• Deallocates memory occupied by the object when it’s deleted.
• A destructor cannot be overloaded and inherited.
• It is called automatically whenever the program terminates.
Destructors
• There is always a single destructor for each class that does not accept any parameters.
• A destructor is based on LIFO.
• The deallocation of memory and destruction is always carried out in the reverse order
of allocation and construction.
• Can be written anywhere in the class definition, but best practise is to define at the end
of the class definition.
• If you don’t create a destructor, compiler creates one for you with empty body.
Destructors
Output:
Pointers
• ∗ (Asterisk sign)
Indirection operator. Access the value of an address.
Pointers
• Write a function that has three character variable containing the names of your
friends. Make pointer variable of these variables to check their memory allocation.