PDA

View Full Version : [SOLVED] What I'am doing wrong?



michalp
June 16th, 2012, 04:55 PM
Hi

I just started with C++ and I did something like this:

main.cpp


int main ( int argc, char** argv )
{
MyClass * First = new MyClass();

First()-> DoSomething();

First->~MyClass();
delete First;

return 0;
}
and MyClass.h


class MyClass
{
public:
MyClass();
virtual ~MyClass();
protected:
private:
AnotherClass * Second;
};
MyClass.cpp


MyClass::MyClass()
{
Second = new AnotherClass();
}

MyClass::~MyClass()
{
Second->~AnotherClass();
delete this->Second;
}
Let the AnotherClass is total empty. What is wrong with this? I got segmentation fault at the end of the program. Could you please help me? As far as I know when I use new then I should have use delete. When I comment the line with delete this->Second; then the program will exit cleary but of course valgrind will report a memory leak.

Zugzwang
June 16th, 2012, 05:16 PM
First of all, note that your code doesn't actually compile.

For example, "First()->DoSomething();" won't work, because First() is neither a function, no has some overloaded operator to make the "()" have any semantic meaning. When next posting something, please make a minimal running example.

Note that destructors are called *automatically* upon deletion of an object. You don't have to do it yourself. For example, change


Second->~AnotherClass();
delete this->Second;

to simply


delete this->Second;


Note that the "this->" is actually not necessary. "delete Second" will do the trick, too.

michalp
June 16th, 2012, 06:12 PM
My mistake my apology. I meant do do it like this:


int main ( int argc, char** argv )
{

MyClass * First = new MyClass();

// First()-> DoSomething();

First->~MyClass();
delete First;
return 0;
}


So thanks fo the tip with destructor, but it doesn't solve my problem with Segmentation fault.

michalp
June 16th, 2012, 06:19 PM
Now I know where was the problem. I called destructor explicitly a then again when I used delete. It runs destructor twice and that is the problem!