Invoke copy constructor - Constructor and Destructor

Q.  Assume class TEST. Which of the following statements is/are responsible to invoke copy constructor?
- Published on 17 Jul 15

a. TEST T2(T1)
b. TEST T4 = T1
c. T2 = T1
d. both a and b
e. All of these

ANSWER: both a and b
 

    Discussion

  • Raj   -Posted on 07 Oct 15
    TEST T2(T1)
    TEST T4 = T1
    A copy constructor is used to initialize an object using another object of the same class. A copy constructor is called when an object is constructed based on another object of the same class.
    Example:
    class CopyConstroctor
    {
    private:
    int x, y;
    public:
    CopyConstroctor(int x1, int y1) { x = x1; y = y1; }

    // Copy constructor
    CopyConstroctor(const CopyConstroctor &p2) {x = p2.x; y = p2.y; }

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

    int main()
    {
    CopyConstroctor obj1(10, 15); // Normal constructor will be called here
    CopyConstroctor obj2 = obj1; // Copy constructor will be called here


    cout << "ojb1.x = " << obj1.getX() << ", obj1.y = " << obj1.getY() << endl;
    cout << "\objp2.x = " << obj2.getX() << ", obj2.y = " << obj2.getY() << endl;

    return 0;
    }

Post your comment / Share knowledge


Enter the code shown above:

(Note: If you cannot read the numbers in the above image, reload the page to generate a new one.)