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.2K
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 2

Thats different...but i wanted to know....if i have a class similar to int....
 
i should not able to do
 
int i;
 
but
 
int i = new int();
 
should be allowed.
 

Regards,
Vikas
  Permalink  
Comments
Sandeep Mewara at 5-Jan-13 3:09am
   
Use comment feature to respond to an answer.
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)

  Print Answers RSS
0 DamithSL 265
1 CPallini 235
2 OriginalGriff 233
3 Maciej Los 175
4 George Jonsson 170
0 OriginalGriff 5,305
1 DamithSL 4,382
2 Maciej Los 3,760
3 Kornfeld Eliyahu Peter 3,470
4 Sergey Alexandrovich Kryukov 2,901


Advertise | Privacy | Mobile
Web03 | 2.8.141216.1 | Last Updated 5 Jan 2013
Copyright © CodeProject, 1999-2014
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