Segment fault /w overloading Constructors

Hi, I'm starting with C++ and I've got some good experience with Java. I try to figure out how things work in C++ in contrast to Java... In the code below I try to overload the constructors of an self made exception class. When creating an object for the first (default) constructor I constantly get this Segment fault.
Could someone please explain why?


Here is my main.cpp code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include "ExceptionA.h"

using namespace std;

/**
 * This is the main. Here is where it all starts.
*/
int main()
{
	ExceptionA obj1; // causes the segment fault
        ExceptionA obj2("Specified Error: ..."); // Also causes the segment fault
	cout << obj1.what() << endl;
        cout << obj2.what() << endl;

	return 0;
}


ExceptionA.h:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;

/**
* This is the template of the class ExceptionA, which is an exception class.
*/
class ExceptionA
{
	private:
		string msg;
	public: 
		string what();
		void setMessage(string);
		ExceptionA();
		ExceptionA(string msg);
		~ExceptionA();
};


ExceptionA.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include "ExceptionA.h"

using namespace std;

string ExceptionA::what()
{
	return msg;
}

void ExceptionA::setMessage(string msg)
{
	this->msg = msg;
}

ExceptionA::ExceptionA()
{
	msg = "Error unknown";
}

ExceptionA::ExceptionA(string msg)
{
	this->msg = msg;
}

ExceptionA::~ExceptionA()
{
	delete this;
}


Output
1
2
3
Error unknown
Specified Error: ...
Segmentation fault (core dumped)
The constructors don't seg fault, but the destructor i.e. delete this; certainly does. Remove that line
Ah right... Thanks!
I guess the this keyword cannot is not linked with all the memory locations and therefore it cannot be deleted?
Topic archived. No new replies allowed.