Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C++/CLI
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 30-Dec-12 5:11am
tasumisra1.1K
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 4

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.
#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>
  Permalink  

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



Advertise | Privacy | Mobile
Web04 | 2.8.150302.1 | Last Updated 8 Feb 2015
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100