Constructors

Estimated reading: 7 minutes 874 Views

What is a Constructor?
In C++, a constructor is a special member function within a class that is automatically invoked when an object of that class is created. Its primary purpose is to initialize the object’s data members or perform any necessary setup for the object. Constructors ensure that the object starts with a valid state.

  1. Constructor Name:
    Constructors have the same name as the class they belong to.
  2. No Return Value:
    Constructors do not return any value, not even void.
  3. Object Initialization:
    Constructors are used to initialize and set up a new object when it is created.

Types of Constructors:

  1. Default/ Empty Constructor:
    Automatically generated by the compiler if no constructor is explicitly defined.
    Initializes object members with default values.
    Syntax: ClassName() { /* Initialization code */ }
    Example 1:

    #include <iostream>
    #include <cstdlib>
    using namespace std;
    class Triangle
    {
        private:
            int base;
            int height;
        public:
            //empty constructor, no arguments are required
            Triangle()
            {
                cout << "first constructor\n";
            }
            void setBase_Height(int b, int h)
            {
                base = b;
                height =h;
            }
            float area()
            {
                return 0.5*base*height;
            }
            void print()
            {
                cout << "base = " << base << endl
                     << "height = " << height << endl
                     << "area = " << area() << endl;
            }
    };
    int main()
    {
        Triangle ob;
        ob.setBase_Height(10, 5);
        ob.print();
    
        return 0;
    }

    An empty constructor is defined (Triangle()). It is automatically called when an object is created and prints “first constructor.”

  2. Parameterized Constructor:
    Accepts parameters during object creation to customize the initial state.
    Provides flexibility for objects to start with different values.
    Syntax: ClassName(type param1, type param2, …) { /* Initialization code */ }
    Example 2:

    #include <iostream>
    #include <cstdlib>
    using namespace std;
    class Triangle
    {
        private:
            int base;
            int height;
        public:
            //empty constructor, no arguments are required
            Triangle()
            {
                cout << "first constructor\n";
                base = 0;
                height = 0;
            }
            //parameterized constructor
            Triangle(int b, int h)
            {
                base = b;
                height = h;
                cout << "parameterized constructor\n";
            }
            void setBase_Height(int b, int h)
            {
                base = b;
                height = h;
            }
            float area()
            {
                return 0.5*base*height;
            }
            void print()
            {
                cout << "base = " << base << endl
                     << "height = " << height << endl
                     << "area = " << area() << endl;
            }
    };
    int main()
    {
        Triangle ob(5, 10);
        //ob.setBase_Height(10, 5);
        ob.print();
    
        return 0;
    }
    

    Parameterized Constructor:

    Accepts parameters (int b and int h) for custom initialization.
    Prints “parameterized constructor” when called.
    The parameterized constructor is employed during object creation, providing initial values for the base and height members.

Example 3:

#include <iostream>
#include <cstdlib>
using namespace std;
class student {
    private:
        char name[20];
        int id;
    public:
        student()
        {
            strcpy_s(name, "no name");
            id = 0;
        }
        student(char n[], int i)
        {
            cout << "parameterized constructor\n";
            strcpy_s(name, n);
            id = i;
        }
        student(char n[])
        {
            strcpy_s(name, n);
        }
        void print()
        {
            cout << "name = " << name << endl;
            cout << "id = " << id << endl;
        }
};
int main()
{
    student ob("Mohammed", 1450902032);
    ob.print();

    return 0;
}

This code defines a class student representing a student with private member variables name and id. The class includes three constructors: an empty constructor, a parameterized constructor with both name and id, and a parameterized constructor with only the name. Let’s break down the code step by step:

– Class Definition: student

class student {
private:
    char name[20];
    int id;

public:
    // Empty Constructor
    student() {
        strcpy_s(name, "no name");
        id = 0;
    }

    // Parameterized Constructor (with name and id)
    student(char n[], int i) {
        cout << "parameterized constructor\n";
        strcpy_s(name, n);
        id = i;
    }

    // Parameterized Constructor (with name only)
    student(char n[]) {
        strcpy_s(name, n);
    }

    // Member Function to print student details
    void print() {
        cout << "name = " << name << endl;
        cout << "id = " << id << endl;
    }
};
  • Empty Constructor:
    Initializes name to “no name” and id to 0.
  • Parameterized Constructor (with name and id):
    Accepts parameters (char n[] and int i).
    Prints “parameterized constructor” when called.
    Sets name and id based on the provided values.
  • Parameterized Constructor (with name only):
    Accepts a parameter (char n[]).
    Initializes only the name attribute.
  • Member Function:
    print: Displays the student’s name and id.

– main Function:

int main() {
    // Object of class student created using the parameterized constructor with name and id
    student ob("Mohammed", 1450902032);

    // Printing the details of the student
    ob.print();

    return 0;
}
  • Object Creation:
    An object ob of type student is created using the parameterized constructor with both name and id.
  • Printing Details:
    The print member function is called to display the details of the student, including the name and id.

The output of this program would be:

parameterized constructor
name = Mohammed
id = 1450902032

This code illustrates the use of multiple constructors in a C++ class. Depending on the provided arguments during object creation, different constructors can be called to initialize the object accordingly.

3. Copy Constructor:

Example 4:

#include <iostream>
using namespace std;
class Copy {
    private:
        int a1, a2, a3, a4, a5, a6, a7, a8;
    public:
        Copy(int aa1, int aa2, int aa3, int aa4,
            int aa5, int aa6, int aa7, int aa8)
        {
            a1 = aa1;
            a2 = aa2;
            a3 = aa3;
            a4 = aa4;
            a5 = aa5;
            a6 = aa6;
            a7 = aa7;
            a8 = aa8;
        }
        Copy(const Copy &a)
        {
            a1 = a.a1;
            a2 = a.a2;
            a3 = a.a3;
            a4 = a.a4;
            a5 = a.a5;
            a6 = a.a6;
            a7 = a.a7;
            a8 = a.a8;
        }
        void print()
        {
            cout << a1 << " " << a2 << " " << a3 << " " << a4 << " "
                 << a5 << " " << a6 << " " << a7 << " " << a8 << " " << endl;
        }
};
int main()
{
    Copy g(1, 2, 3, 4, 5, 6, 7, 8);
    g.print();
    Copy h(g);
    h.print();

    return 0;
}

This code defines a class Copy with two constructors – one for initializing an object with specific values and another for performing a deep copy of an existing object. Let’s break down the code:

– Class Definition: Copy

class Copy {
private:
    int a1, a2, a3, a4, a5, a6, a7, a8;

public:
    // Parameterized Constructor for Initialization
    Copy(int aa1, int aa2, int aa3, int aa4,
         int aa5, int aa6, int aa7, int aa8) {
        a1 = aa1;
        a2 = aa2;
        a3 = aa3;
        a4 = aa4;
        a5 = aa5;
        a6 = aa6;
        a7 = aa7;
        a8 = aa8;
    }

    // Copy Constructor for Deep Copy
    Copy(const Copy &a) {
        a1 = a.a1;
        a2 = a.a2;
        a3 = a.a3;
        a4 = a.a4;
        a5 = a.a5;
        a6 = a.a6;
        a7 = a.a7;
        a8 = a.a8;
    }

    // Member Function to Print Object Details
    void print() {
        cout << a1 << " " << a2 << " " << a3 << " " << a4 << " "
             << a5 << " " << a6 << " " << a7 << " " << a8 << " " << endl;
    }
};
  • Parameterized Constructor:
    Initializes the object with specific values provided as arguments.
  • Copy Constructor:
    Performs a deep copy of an existing object (Copy &a).
    Copies each member variable of the source object to the new object.
  • Print Function:
    Displays the values of the object’s member variables.

– main Function:

int main() {
    // Creating an object 'g' and initializing it with specific values
    Copy g(1, 2, 3, 4, 5, 6, 7, 8);
    
    // Printing the details of object 'g'
    g.print();

    // Creating another object 'h' and initializing it by performing a deep copy of 'g'
    Copy h(g);

    // Printing the details of object 'h'
    h.print();

    return 0;
}
  • Object Creation (g):
    An object g of type Copy is created and initialized with specific values.
  • Printing Details (g):
    The print member function is called to display the details of object g.
  • Object Creation (h):
    Another object h is created and initialized by performing a deep copy of object g using the copy constructor.
  • Printing Details (h):
    The print member function is called to display the details of object h

The output of this program would be:

1 2 3 4 5 6 7 8 
1 2 3 4 5 6 7 8 

This code illustrates the usage of a copy constructor to create a new object with the same values as an existing object, ensuring a deep copy of the data.

Share this

Constructors

Or copy link

CONTENTS
English