Click here to Skip to main content
15,867,453 members
Articles / Programming Languages / C++
Tip/Trick

Difference between this->CMyClass::CMyClass() and CMyClass()

Rate me:
Please Sign up or sign in to vote.
1.00/5 (3 votes)
30 Nov 2011CPOL 17.6K   1   6
Why does it have to be this complicated to call a constructor
The purpose of this writing is to illustrate how constructors can be called in Visual Studio.
I am not suggesting to call constructors explicitly. Here is the queston:

Why does it have to be this complicated to call a constructor:
C++
this->CMyClass::CMyClass();

instead of just CMyClass();

See function f() in the following example.
C++
struct CMyClass
{     
	int mi;
	CMyClass() 
	{
		printf("%d\n", mi);
	}
	void f()  
	{ 
		this->CMyClass::CMyClass(); 
	}
};

In this->CMyClass::CMyClass();
'this' is required; Otherwise it creates a temporary object instead of calling constructor.
'CMyClass::' is required; otherwise CMyClass is interpreted as a type instead of a constructor.

I also made a test case on my blog

License

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


Written By
Engineer
Canada Canada
This member doesn't quite have enough reputation to be able to display their biography and homepage.

Comments and Discussions

 
GeneralThis code runs as expected on Visual Studio 2010, which has ... Pin
RioWing29-Nov-11 5:52
RioWing29-Nov-11 5:52 
GeneralReason for my vote of 1 I don't know which compiler you used... Pin
Alex Cohn29-Nov-11 2:05
Alex Cohn29-Nov-11 2:05 
GeneralReason for my vote of 1 There is no reason to call the const... Pin
matt_taws29-Nov-11 0:56
matt_taws29-Nov-11 0:56 
GeneralReason for my vote of 1 What about the "placement new" opera... Pin
giulicard28-Nov-11 20:49
giulicard28-Nov-11 20:49 
GeneralIt's not clear what you expect to happen. You have a class ... Pin
Jon Summers28-Nov-11 8:42
Jon Summers28-Nov-11 8:42 
GeneralRe: I am only trying to illustrate how to call a constructor. A ... Pin
RioWing28-Nov-11 9:42
RioWing28-Nov-11 9:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.