Click here to Skip to main content
15,117,779 members
Articles / Programming Languages / C++
Tip/Trick
Posted 24 Nov 2011

Tagged as

Stats

15.8K views
1 bookmarked

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
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)

Share

About the Author

RioWing
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 6:52
MemberRioWing29-Nov-11 6:52 
GeneralReason for my vote of 1 I don't know which compiler you used... Pin
Alex Cohn29-Nov-11 3:05
MemberAlex Cohn29-Nov-11 3:05 
GeneralReason for my vote of 1 There is no reason to call the const... Pin
matt_taws29-Nov-11 1:56
Membermatt_taws29-Nov-11 1:56 
GeneralReason for my vote of 1 What about the "placement new" opera... Pin
giulicard28-Nov-11 21:49
Membergiulicard28-Nov-11 21:49 
GeneralIt's not clear what you expect to happen. You have a class ... Pin
Jon Summers28-Nov-11 9:42
MemberJon Summers28-Nov-11 9:42 
GeneralRe: I am only trying to illustrate how to call a constructor. A ... Pin
RioWing28-Nov-11 10:42
MemberRioWing28-Nov-11 10: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.