Q:

What is a copy constructor in c++?

0

What is a copy constructor?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer:

A copy constructor is a member function that initializes an object using another object of the same class. If you will not create your own copy constructor then the compiler creates a default copy constructor for you.

Syntax of copy constructor:

ClassName (const ClassName &old_obj);

Example,

#include<iostream>
using namespace std;
class Foo
{
private:
    int x, y;
public:
    Foo(int x1, int y1)
    {
        x = x1;
        y = y1;
    }
    // Copy constructor
    Foo(const Foo &rOldObj)
    {
        x = rOldObj.x;
        y = rOldObj.y;
    }
    int getX()
    {
        return x;
    }
    int getY()
    {
        return y;
    }
};
int main()
{
    // Normal constructor is called here
    Foo obj1(10, 15);
    // Copy constructor is called here
    Foo obj2 = obj1;
    //Print obj1 values
    cout << "obj1.x = " << obj1.getX();
    cout << "\nobj1.y = " << obj1.getY();
    //Print obj2 values
    cout << "\n\nobj2.x = " << obj2.getX();
    cout << "\nobj2.y = " << obj2.getY();
    return 0;
}

Output:

obj1.x = 10
obj1.y = 15
 
obj2.x = 10
obj2.y = 15

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ Interview Questions For Experienced

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
When are copy constructors called in C++?... >>
<< When do we use the Initializer List in C++?...