calling constructor from constructor set pointer to null!

VS 2012 / Windows 7 64 bit

class
1
2
3
4
5
6
7
8
9
class myclass
{
public:
    myclass(){/*stuff here*/}
    myclass(int* p) {MyPointer = p; myclass()}
private:
    int* MyPointer

};


in main
1
2
int MyInt = 5;
myclass* mc = new myclass(&MyInt);


it works until the myclass(int* p) calls myclass()
then the MyPointer will become CCCCCCCC (NULL value)!

is there a way to stop the second constructor from resetting the pointer value to null?
Yes, use an initialization list (or simply call the other constructor first):
1
2
3
4
5
6
7
myclass(int* p)
    : myclass(), MyPointer(p)
{}

// OR

myclass(int* p) { myclass(); MyPointer = p; }
You can't call a constructor like that. When you do myclass(); this creates a new myclass object using the default constructor, but you don't do anything with this object so it's pretty useless.

C++11 supports delegating constructors.
 
myclass(int* p) : myclass() {MyPointer = p;}
But note that this will call the myclass() constructor before assigning the pointer.
Thank you kind Sirs...

the problem that I use the value of that pointer in the myclass() constructor to do some stuff so calling the second constructor before assigning wont help me...
I think i will just do the old way of moving shared code to a separate function and call that function from the two constructors.

yours....
Topic archived. No new replies allowed.