What is constructor? Explain the concept of default and default copy with suitable example.

This answer is restricted. Please login to view the answer of this question.

Login Now

A constructor is a special type of member function of a class which initializes objects of a class. In C++, Constructor is automatically called when object(instance of class) create. It is special member function of the class because it does not have any return type.

There are two types of constructors

  1. Default Constructor
  2. Parameterized Constructor
  3. Copy Constructor

1. Default Constructor:

Default constructor is the constructor which doesn’t take any argument. It has no parameters.

#include <iostream>
using namespace std;

class construct{
    public:
    int a, b;

    // Default Constructor
    construct(){
        a = 10;
        b = 20;
    }
};

int main(){
    construct c;
    cout << "a: " << c.a << endl
        << "b: " << c.b;
    return 1;
}

The output of above code is

a: 10
b: 20

if we do not define any constructor explicitly, the compiler will automatically provide a default constructor implicitly.

2. Copy Constructor:

A copy constructor is a member function that initializes an object using another object of the same class. A copy constructor has the following general function prototype:

ClassName (const ClassName &old_obj);

Following is a simple example of copy constructor.

#include<iostream>
using namespace std;

class Point
{
private:
    int x, y;
    public:
    Point(int x1, int y1) { x = x1; y = y1; }

    // Copy constructor
    Point(const Point &p1) {x = p1.x; y = p1.y; }

    int getX() { return x; }
    int getY() { return y; }
};

int main(){
    Point p1(10, 15); // Normal constructor is called here
    Point p2 = p1; // Copy constructor is called here

    // Let us access values assigned by constructors
    cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
    cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();

    return 0;
}

The output of above program is

p1.x = 10, p1.y = 15
p2.x = 10, p2.y = 15

The argument on copy constructor must passed as reference because It is called when an object is passed by value. Copy constructor itself is a function. So if we pass an argument by value in a copy constructor, a call to copy constructor would be made to call copy constructor which becomes a non-terminating chain of calls. Therefore compiler doesn’t allow parameters to be passed by value.

If you found any type of error on the answer then please mention on the comment or report an answer or submit your new answer.
Leave your Answer:

Click here to submit your answer.

Discussion
0 Comments
  Loading . . .