How many times the destructor of the test class will be called in the following program?
#include <iostream>
using namespace std;
class test
{
public:
	test(int param)
	{
		i=param;
	}
	test(test &obj)
	{
		i=obj.i;
	}
	~test()
	{
		cout << "~test()" << endl;
	}
private:
	int i;
};
void func1(test obj)
{
	cout << "func1()" << endl;
}
void func2(test &obj)
{
	cout << "func2()" << endl;
}
int main()
{	
	test a(1);
	test b(2);
	test c(3);
	
	func1(a);
	func2(b);

	return 0;
}
Explanation
The destructor is called 4 times:
3 times for variables of type test a, b, c;
1 time after exiting the func1() function, because the variable a is passed by value, therefore the copy constructor creates a copy of the variable a, for which the destructor is automatically called when the function exits;
when the func2() function exits, the destructor is not called, because the variable is passed by reference, its copy is not created.

Следи за CodeGalaxy

Мобильное приложение Beta

Get it on Google Play
Обратная Связь
Cosmo
Зарегистрируйся сейчас
или Подпишись на будущие тесты