-
C++ programming
Hi all,
My question is, Is it legal to use 'this' pointer inside a constructor? for example
class Test
{
private
int var;
public
void Test(int); // constructor
};
Test *ptrToTest; // defined outside the class definition
void Test::Test(int) // constructor
{
var = int;
ptrToTest = this ; // is this legal to do?
}
Thank you all in advance for your help.
Anna
-
Re: C++ programming
I guess you is legal(it will not generate any run time error) but according to me the better way to go about it will be
Test *ptrToTest = new Test;
Thanks
Chetan
Nothing is impossible.
-
Re: C++ programming
It is not safe to use pointer assignment in the constructor of the class.The reason is because you can not use try and catch block inside the constructor.So your application may be crash if it encounter any any sort of exception due to pointer assignment.
ksheeraj
39639,Leslie St.
Apt #157
Fremont USA 94538
-
Re: C++ programming
Hi ksheeraj
Yes, I am Pretty sure that you can use exception handling in the constructor in fact I guess that is the main reason why Exception handling is introduced in the C++, other wise if some error occurs in the constructor then there is no way for the user of this class to determine if there is any error in the constructor unless
1) there is some test error function in the class that user need to call to see if there is any error occured in the constructor. But in this case user may forget to call this test function so this method is not full proof.
2) Any class should not do any thing in the constructor and supply another function to make initialization. This method Defeats the concept of constructor so in my openion this method should not be used unless it is very un avoidable.
3) So the remaining and the only effective method is to introduce exception handling.
Following is the piece of code that demonstrates the excpetion handling in the constructor.
Please feel free to comment on this as comments are always welcome because they make you think.
Thanks
Chetan
#include <stdio.h>
class CMyPtr
{
public:
CMyPtr(char* pString)
{
if( pString == NULL) // Some condition to throw an exception
throw("Null pointer is passed so I am throwing this exception\n");
this->szPtr = pString;
printf(this->szPtr);
}
private:
char* szPtr;
};
main()
{
char* szString = "Valid Pointer\n";
try{
CMyPtr Ptr1(szString); // This will not throw an excpetion
CMyPtr Ptr2(NULL); // But this will throw an exception
}
catch(char* szSomeException)
{
printf(" The excpetion received is : %s", szSomeException);
}
return 0;
}
Practice makes the man perfect.
-
Re: C++ programming
All right but can I ahve something like this in the constructor:
Class SomeServer(LPUNKNOWN pUnk)
{
SOMESERVERLib::ISomeDispatchPtr spDispatch;
spDispatch = pUnk;
//And this calls get failed and throes Com exception who will handle it!!!!
}
Ksheeraj
39639,Leslie St.
Apt #157
Fremont USA 94538