• 0

Assertion failed


Question

So I was studying c++ and made a very simple program to illustrate was I learned.But i always get assertion failed when the program ends. I know this is probably due to the destructors.Here's the code.

#include <iostream>
#include <stdio.h>
#include <string.h>

using namespace std;


class ABC
{
protected:
	char *message;
	int nr;
public:
	ABC();
	ABC(int,char*);
	virtual ~ABC();
	char* getmessage();
	int getnr();
};

ABC::ABC()
{
	this->message = new char[50];
	strcpy(this->message,"\n implicit constructor  ABC");
	this->nr = 1;
}

ABC::ABC(int n, char *txt)
{
	this->message = new char[50];
	this->nr = n;
	strcpy(this->message,txt);
}

ABC::~ABC()
{
	cout<<"\nDestructor ABC";
	if(message != NULL)
	{
		delete[] message;
		message = NULL;
	}
}

int ABC::getnr()
{
	return this->nr;
}

char* ABC::getmessage()
{
	return this->message;
}

class ABCE: public ABC
{
protected:
	int aux;
public:
	int getaux();
	ABCE();
	ABCE(int,char*,int);
	virtual ~ABCE();
};

ABCE::~ABCE()
{
	cout<<"\nDestructor ABCE";
	if(message != NULL)
	{
		delete[] message;
		message = NULL;
	}
}

ABCE::ABCE()
{
	this->message = new char[50];
	strcpy(this->message,"implicit constructor ABC");
	this->aux = 0;
	this->nr = 0;
}

ABCE::ABCE(int n,char *txt,int au)
{
	this->message = new char[50];
	this->aux = au;
	this->nr = n;
	strcpy(this->message,txt);
}

int main(void)
{
	ABC aaa;
	cout<<aaa.getmessage();
	ABC bbb(10,"\n explicit constructor");
	cout<<bbb.getmessage();
	bbb = aaa;
	cout<<bbb.getmessage();
	bbb.getmessage()[4] = '4';
	cout<<bbb.getmessage();
	cout<<aaa.getmessage();
	ABCE abba;
	cout<<abba.getmessage();
	ABCE *abb = new ABCE();
	delete abb;
	return 0;
}

Ok,problem solved,I didn't have a copy constructor defined and when I copied aaa to bbb,i also copied the pointed which the program tried to delete it twice.

Edited by Cold Blood
Link to comment
Share on other sites

0 answers to this question

Recommended Posts

There have been no answers to this question yet

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.