Click here to Skip to main content
15,666,726 members
Articles / Programming Languages / C++
Posted 24 Nov 2011

Tagged as


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:

instead of just CMyClass();

See function f() in the following example.
struct CMyClass
	int mi;
		printf("%d\n", mi);
	void f()  

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


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

Written By
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 
It's not clear what you expect to happen. You have a class (a struct can viewed as a class having all its members public) named CMyClass. It has a function f();
Calling a class constructor within a member of that class doesn't make a lot of sense.
Why not do this?
CMyclass oMyClass; // Constructor called automatically
oMyClass.f (); // ???
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.