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.]
/*
* 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
*/
Comments
Leave a comment