Click here to Skip to main content
15,884,388 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Folks,

Help me to find a way to avoid instantiation of a c++ class on stack but can be instantiated on heap.

Regards,
Vikas
Posted

 
Share this answer
 
 
Share this answer
 
The functionality can be achieved by making the constructor private. You will still need a static function to get the heap allocated handle. This is how i usually do it (the same behavior you asked for)

P.S. this is not complete code, just half baked solution to show you the direction.
C++
#include <iostream>

using namespace std;

class A
{
private:
	A()
	{

	}
	
public:

	static A* CreateAndGetInstancePointer()
	{
		return new A();
	}

	int test()
	{
		return 2;
	}

};

int _tmain(int argc, _TCHAR* argv[])
{
	// This will give compile time error
	//A a;
	
	//cout << a.test();

	A *pa = A::CreateAndGetInstancePointer();
	
	cout << pa->test();
	
	return 0;
}

</iostream>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900