Unit 3 - C++
Unit 3 - C++
Unit III
                                          Constructor And Destructor
❖      Introduction to constructor:
    ⚫ In C++, a constructor is a special member
        function that is automatically called
        when an object of a class is created.
    ⚫ It is used to initialize the object's data
        members and perform any necessary
        setup operations. Constructors have the
        same name as the class and do not have
        a return type, not even void.
    ⚫ Constructors can be overloaded, meaning
        we can have multiple constructors with
        different parameters. This allows for
        flexibility in creating objects of the class.
Syntax:
class MyClass {
public:
    // Constructor
    MyClass() {
        // Constructor code
    }
};
    ◼ Characteristics of Constructor:
        1.   Same Name as Class:
                 ⚫    Constructors have the same name as the class they belong to.
                 ⚫    This is how the compiler identifies them as constructors.
        2.   No Return Type:
                 ⚫    Unlike regular functions, constructors don't have a return type, not even void.
                 ⚫    This is because constructors are automatically called when an object is created, and their
                      purpose is to initialize the object rather than return a value.
        3.   Automatic Invocation:
                 ⚫    Constructors are automatically invoked when an object of the class is created.
                By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
                                                                                           Page 1 of 19
                               Object-oriented programming using C++
                                                Unit III
                                       Constructor And Destructor
//Creating a Class
class Construct
{
    public:
        //Creating a Constructor having same name as Class Name
        Construct()
        {
            int a=10;
            cout<<"Constructor Created The value of a is "<<a<<endl;
        }
};
int main()
{
   Construct con; //Creating a object of a class
                   //It will automatically call a Constructor
}
                                               Output :
                                               Constructor Created The value of a is 10
❖ Types of a constructor:
              By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
                                                                                            Page 2 of 19
                                    Object-oriented programming using C++
                                                   Unit III
                                          Constructor And Destructor
Program:
#include <iostream>
using namespace std;
class DefCon {
public:
    int num;
    char character;
      // Default constructor
      DefCon() {
          num = 0; // Default value for int
          character = 'A'; // Default value for char
      }
};
int main() {
    DefCon obj;
    cout << "num: " << obj.num << endl;
                 By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
                                                                                             Page 3 of 19
                                 Object-oriented programming using C++
                                                  Unit III
                                         Constructor And Destructor
Program:
//*** Program to demonstrate Parameterized Construction **//
#include <iostream>
using namespace std;
class ParCons {
public:
    int num;
    char character;
                                           Output :
                                                             num: 0
     // Parameterized constructor
     ParCons(int num, char ch) {                             character: A
         num = num;
         character = ch;
     }
};
int main() {
    ParCons obj(10, 'B');
    cout << "num: " << obj.num << endl;
    cout << "character: " << obj.character << endl;
               By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
                                                                                             Page 4 of 19
                                Object-oriented programming using C++
                                                Unit III
                                       Constructor And Destructor
         return 0;
}
Program:
#include <iostream>
using namespace std;
class ParCons {
public:
    int num;
    char character;
   float fnum;
         // Parameterized constructor
         ParCons(int n, char ch) {
             num = n;
             character = ch;
     }
         // Constructor Overloading
         ParCons(int n, char ch, float f) {
             num = n;
             character = ch;
             fnum = f;
         }
};
int main() {
    ParCons obj1(10, 'B');
   ParCons obj2(20, 'C', 20.5);
                                                             Output :
    cout << "num: " << obj1.num << endl;                     num: 10
   cout << "character: " << obj1.character <<
                                                             character: B
endl << endl;
                  By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
                                                                                  Page 5 of 19
                                  Object-oriented programming using C++
                                                      Unit III
                                             Constructor And Destructor
   3. Copy Constructor:
        ⚫   A copy constructor is a special
            constructor that initializes a new
            object as a copy of an existing object.
        ⚫   It is invoked when a new object is
            created from an existing object, either
            by    direct   initialization,    function
            argument passing, or returning an
            object by value.
        ⚫   If   we    don't    provide       a   copy
            constructor explicitly, the compiler
            generates one for us, which performs
            a shallow copy of the data members.
Syntax:
class CopyCons {
public:
    // Copy constructor
    CopyCons(const CopyCons& obj) {
        // Constructor code to perform copy
    }
};
Program:
#include <iostream>
using namespace std;
class CopyCons {
public:
    int num;
   char character;
      // Copy constructor
      CopyCons(const CopyCons& obj) {
          num = obj.num;
                 By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
                                                                                 Page 6 of 19
                                   Object-oriented programming using C++
                                                    Unit III
                                           Constructor And Destructor
             character = obj.character;
     }                                                                  Output :
};
                                                                        obj1 num: 10
int main() {                                                            obj1 character: B
    CopyCons obj1(10, 'B');
   CopyCons obj2 = obj1;
                                                                        obj2 num: 10
    cout << "obj1 num: " << obj1.num << endl;
   cout << "obj1 character: " << obj1.character                         obj2 character: B
<< endl <<endl;
❖ Destructors:
         ⚫    In C++, a destructor is a special member function that is automatically called when an object of a
              class is destroyed or goes out of scope.
         ⚫    Its primary purpose is to perform cleanup operations such as releasing resources (like dynamic
              memory allocation) or closing file handles that were acquired during the object's lifetime.
         ⚫    Destructors have the same name as the class preceded by a tilde (~) , and they do not take any
              arguments.
                  ◼    Use Cases for Destructors:
                       1.   Resource Deallocation: Destructors are commonly used to release resources acquired
                            by the object during its lifetime, such as dynamic memory allocation, file handles,
                            database connections, etc.
                       2.   Cleanup Operations: Destructors can perform cleanup operations necessary for the
                            proper functioning of the object, such as resetting internal states or closing open
                            connections.
                       3.   Custom Logging and Debugging: Destructors can also be used for custom logging or
                            debugging purposes, allowing us to track the lifecycle of objects in our program.
Syntax:
class ClassName {
public:
    // Constructor
    ClassName() {
                 By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
                                                                                             Page 7 of 19
                           Object-oriented programming using C++
                                           Unit III
                                  Constructor And Destructor
         // Constructor code
     }
     // Destructor
     ~ClassName() {
         // Destructor code
     }
};
Program:
#include <iostream>
using namespace std;
class Resource {
public:
     // Constructor
     Resource() {
         cout << "Resource acquired" << endl;
   }
     // Destructor                                             Output :
     ~Resource() {                                             Resource acquired
         cout << "Resource released" << endl;
     }                                                         Resource released
};
int main() {
    // Creating an object of class Resource
   Resource obj;
Program 2:
#include<iostream>
using namespace std;
class demo
{
    int a=10,b=20;
public :
    demo()
    {
         cout<<"Calling constructor"<<endl;
         a=50;
             By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
                                                                             Page 8 of 19
                                     Object-oriented programming using C++
                                                     Unit III
                                            Constructor And Destructor
               b=70;                                                      Output :
    }                                                                     Calling constructor
    void display()                                                        50 , 70
    {
                                                                          50 , 70
        cout<<a<<" , "<<b<<endl;
                                                                          50 , 70
    }
    ~demo()                                                               50 , 70
                   By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
                                                                                              Page 9 of 19
                                    Object-oriented programming using C++
                                                        Unit III
                                               Constructor And Destructor
 ◼ Order of Constructors:
   ◆ Base Class Constructor:
          ⚫    When we create an object of a derived
               class, the constructor of the base class
               is called first.
          ⚫    This ensures that the base class
               subobject is initialized before the
               derived class subobject.
          ⚫    If the base class has its own base
               classes, their constructors are called in
               the same order as described here.
   ◆ Derived Class Constructor:
          ⚫    After the base class constructor is
               executed, the constructor of the
               derived class is called.
          ⚫    The     derived      class      constructor
               initializes the members specific to the
               derived class.
   ◼ Order of Destructors:
   ◆ Derived Class Destructor:
      ⚫       When an object of a derived class goes out of scope or is explicitly destroyed, the destructor of the
              derived class is called first.
          ⚫    This ensures that resources allocated by the derived class are deallocated before the resources
               allocated by the base class.
                 By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
                                                                                              Page 10 of
                                                                                              19
                              Object-oriented programming using C++
                                               Unit III
                                      Constructor And Destructor
class A {
public:
     A() {
         cout << "A constructed" << endl;
   }
     ~A() {
         cout << "A destroyed" << endl;
     }
};
class B {
public:
     B() {
         cout << "B constructed" << endl;
   }
     ~B() {
         cout << "B destroyed" << endl;
     }
};
class C {
public:
     C() {
         cout << "C constructed" << endl;
   }
     ~C() {
         cout << "C destroyed" << endl;
     }
};
int main() {
    cout << "Creating object for Class C..." << endl;
    C c; // Create object of class C
    cout << "Creating object for Class A..." << endl;
    A a; // Create object of class A
             By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
                                                                                         Page 11 of
                                                                                         19
                                     Object-oriented programming using C++
                                                      Unit III
                                             Constructor And Destructor
Output :
Creating object for Class C...
C constructed
Creating object for Class A...
A constructed
Creating object for Class B...
B constructed
Exiting main function...
B destroyed
A destroyed
C destroyed
               By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
                                                                               Page 12 of
                                                                               19
                                     Object-oriented programming using C++
                                                     Unit III
                                            Constructor And Destructor
                      ⚫ It dynamically allocates memory for a single object of the specified data type on the heap.
                      ⚫ Returns a pointer to the allocated memory.
          2.    delete Operator:
                      ⚫ Deallocates memory previously allocated using new.
                      ⚫ Prevents memory leaks by releasing dynamically allocated memory.
Syntax:
type *pointer_name = new type;
delete pointer_variable;
Program:
#include <iostream>
using namespace std;
int main() {
    // Dynamically allocate memory for a single integer
    int *ptr = new int;
     // Deallocate memory
    delete ptr;
                                                           Output :
     return 0;                                             Dynamically allocated integer: 10
}
                    By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
                                                                                             Page 13 of
                                                                                             19
                                   Object-oriented programming using C++
                                                    Unit III
                                           Constructor And Destructor
              ⚫ Since operator overloading allows us to change how operators work, we can redefine how the +
                  operator works and use it to add the complex numbers of c1 and c2
Syntax:
class className {
    ... .. ...
    public
       returnType operator symbol (arguments) {
           ... .. ...
       }
    ... .. ...
};
Where :
   ➢ returnType is the return type of the function.
   ➢ operator is a keyword.
   ➢ symbol is the operator we want to overload. Like: +, <, -, ++, etc.
   ➢ arguments is the arguments passed to the function.
                  By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
                                                                                               Page 14 of
                                                                                               19
                                   Object-oriented programming using C++
                                                    Unit III
                                           Constructor And Destructor
                        ⚫   Although it's less commonly overloaded compared to unary and binary operators, it can
                            still be overloaded if necessary.
                        ⚫   However, its overloading syntax is not as straightforward as unary and binary operators.
                By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
                                                                                           Page 15 of
                                                                                           19
                                 Object-oriented programming using C++
                                                 Unit III
                                        Constructor And Destructor
           ⚫ Unary operator overloading in C++ involves defining custom behavior for unary
              operators (operators that operate on a single operand) when they are used with objects of
              user-defined classes.
           ⚫ This allows us to extend the functionality of our classes and provide intuitive syntax for
              operations.
Program:
#include<iostream>
using namespace std;
class Unary {
   int a, b, c;
public :
     // Constructor to initialize object with values of a, b, and c
     Unary(int x, int y, int z) {
         a = x;
         b = y;
         c = z;
         cout << a << " " << b << " " << c << endl;
   }
int main() {
   cout << "\n Original Values: " << endl;
      // Create an object u of class Unary with values (10, -20, 30) and print them
     Unary u(10, -20, 30);
    // Apply unary negation (-) operator to object u, create new object u2 with
negated values
   Unary u2 = -u;
                  By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
                                                                                    Page 16 of
                                                                                    19
                               Object-oriented programming using C++
                                               Unit III
                                      Constructor And Destructor
    // Apply unary plus (+) operator to object u, create new object u3 with
original values
   Unary u3 = +u;
     return 0;
}
     Output :
     Original Values:
     10 -20 30
     Using - overloaded operator:
     -10 20 -30
     Using + overloaded operator:
     10 -20 30
                By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
                                                                                  Page 17 of
                                                                                  19
                                  Object-oriented programming using C++
                                                Unit III
                                       Constructor And Destructor
class Complex {
private:
    double real;
   double imag;
public:
     // Constructor
     Complex(double r, double i) {
         real = r;
         imag = i;
   }
int main() {
    // Create two complex numbers
    Complex c1(2.5, 3.5);
   Complex c2(1.5, 2.5);
                 By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
                                                                                  Page 18 of
                                                                                  19
                           Object-oriented programming using C++
                                           Unit III
                                  Constructor And Destructor
                                               Output :
    return 0;
}                                              Real: 4, Imaginary: 6
******************
Reference: The contents present in the notes have also been taken from WWW (world
wide Web resources) and compiled in the notes.
Note: Students are advised to read the notes carefully and build the concept. And practice
in the perspective approach.
***********************
             By, Mritunjay Kr. Ranjan. & Shilpi Saxena, SOCSE -Sandip University, Nashik
                                                                             Page 19 of
                                                                             19