Answer to Question #240233 in C++ for Anupam Moharana

Question #240233

Q1. Consider the code given below.

 

How many times the following are invoked:

I) Default constructor

II) Parameterized constructor

III) Copy constructor

IV) Destructor

 

class test

{   int a;

public:

test(){a=0;}

test(int x) {a=x;}

test(const test &T){a=T.a;}

~test(){ }

test add(test X)

{ test T;

     T.a=a+X.a;

     return 0;

}

};

int main()

{ test t1(5),t2(10),t3;

  t3=t1.add(t2);

  return 0;

}

[Assume all the header files and namespaces included.]


1
Expert's answer
2021-09-22T00:00:34-0400
/*
* Let's change the code by adding a trace of the invocation
* of the constructors and the class destructor
*/


#include <iostream>
class test
{
    int a;
public:
    test() { a = 0;
    std::cout << " Default constructor called "<<"\n";
    }


    test(int x) { a = x;
    std::cout << "Parameterized constructor called" << "\n";
     }


    test(const test &T) {
        a = T.a;
        std::cout << "Copy constructor called" << "\n";
    }


    ~test() {
        std::cout << "Destructor called "<<std::endl ;
    }


    test add(test X)


    {
        test T;
        T.a = a + X.a;
        return 0;
    }


};

int main()


{
   test t1(5), t2(10), t3;
   t3 = t1.add(t2);
    return 0;
}
/*Result of code execution:
    Parameterized constructor called
    Parameterized constructor called
    Default constructor called
    Copy constructor called
    Default constructor called
    Parameterized constructor called

    Destructor called
    Destructor called
    Destructor called
    Destructor called
    Destructor called
    Destructor called
*/
/*                 Answer:
            Number of calls:
           I) Default constructor - 2
           II) Parameterized constructor -3
           III) Copy constructor -1
           IV) Destructor -6
*/

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS