473,669 Members | 2,335 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

new and delete help for classes

I have an array of pointers to class Shape.

I create 4 items and display their values.

shapes[0 - 3]
Shape *shapes[SIZE];

shapes[0] = new Shape (p1);
shapes[1] = new Triangle (p1);
shapes[2] = new Polygon (p2);

p2.push_back( Point( 210, 210) );
shapes[3] = new Polygon (p2);

sListSize = 4;

// --== This is what is causing my program to crash - but why? ==--
// Please help
for(int i = 0; i < sListSize; i ++)
delete shapes[i];

But when I try to delete them, The program crashes after item 0.
Please find attached the code below:
//----------------------------------------------------------------------------------------------------------
// .h file
//----------------------------------------------------------------------------------------------------------
class Point
{
public:
int x, y;
Colour col;

public:
Point(void) { x = y = 100; col.r = col.g = col.b = 255; }
Point(int iX, int iY, Colour iCol);
Point(int iX, int iY);
string GetInfo(void);

// operators
Point operator=(const Point &rhs);
bool operator==(cons t Point &rhs);
bool operator!=(cons t Point &rhs);
bool operator<( const Point & rhs) { return this->y < rhs.y; }
};

class Shape
{
public:
vector<PointpL;
vector<Line eL;

public:
Shape(vector<Po intpList) : pL(pList) { cout << "Shape constructor" <<
endl; }
Shape(void) {}
~Shape() { cout << "Shape Destructor" << endl; }

// Member functions
void SetColour(Colou r);

// Virtual functions
virtual string GetInfo(void);
virtual void Draw(void);

// Sorting routines
void SortOnY(void);
void SortOnX(void);
};

class Triangle : virtual public Shape
{
public:
Triangle(vector <PointpList, unsigned int fType = 0) :
Shape(pList), fillType(fType) { SortOnY(); cout << "Triangle constructor"
<< endl; }

~Triangle() { cout << "Triangle destructor" << endl; }
void Draw(void);
string GetInfo(void);
private:
unsigned int fillType;
};

// Member of Shape and Triangle
class Polygon : virtual public Shape, public Triangle
{
public:
Polygon(vector< PointpList, unsigned int fType = 0) :
Triangle(pList, fType), Shape(pList) { SortOnX(); }

~Polygon() { cout << "Polygon destructor" << endl; }
void Draw(void);
string GetInfo(void);
};

//----------------------------------------------------------------------------------------------------------
// .cpp file
//----------------------------------------------------------------------------------------------------------
Point::Point(in t iX, int iY, Colour iCol)
{
x = iX;
y = iY;
col = iCol;
}

Point::Point(in t iX, int iY)
{
x = iX;
y = iY;
col.r = col.b = col.g = 255;
}

string Point::GetInfo( void)
{
string s;
char buff[200];
sprintf(buff, "Point (%3d,%3d) - Col_RGB: [%3d,%3d,%3d]", x, y, col.r,
col.g, col.b);
s = buff;
return(s);
}

Point Point::operator =(const Point &rhs)
{
if(this == &rhs)
return(*this);

x = rhs.x;
y = rhs.y;
col = rhs.col;

return(*this);
}

bool Point::operator ==(const Point &rhs)
{
if(rhs.x == x && rhs.y == y)
return(true);
else
return(false);
}

bool Point::operator !=(const Point &rhs)
{
if(rhs.x != x && rhs.y != y)
return(true);
else
return(false);
}

// ------------------------------------------------------------------
// --== LINE ==--
// ------------------------------------------------------------------
// LINE --Constructor 1
Line::Line(Poin t iP1, Point iP2)
{
p1 = iP1;
p2 = iP2;
}

string Line::GetInfo(v oid)
{
string s;
char buff[200];

return(s);
}
// ------------------------------------------------------------------
// --== SHAPE ==--
// ------------------------------------------------------------------
// Sorting functions
bool lessX(const Point &p1, const Point &p2) { return(p1.x < p2.x); }
bool lessY(const Point &p1, const Point &p2) { return(p1.y < p2.y); }

void Shape::SortOnX( void) { sort (pL.begin(), pL.end(), lessX); }
void Shape::SortOnY( void) { sort (pL.begin(), pL.end(), lessY); }

void Shape::SetColou r(Colour c)
{
for(int i = 0; i < pL.size(); i ++)
pL[i].col = c;
}

string Shape::GetInfo( void)
{
string s;
char buff[200];
sprintf( buff, "Shape - pointCnt: %d", pL.size() );
s = buff;

for(int i = 0; i < pL.size(); ++ i)
s += string("\n\t") + pL[i].GetInfo().c_st r();

return(s);
}

void Shape::Draw(voi d) { cout << "Shape Draw" << endl; }

// ------------------------------------------------------------------
// --== SHAPE ==--
// ------------------------------------------------------------------
void Triangle::Draw( ) { cout << "Triangle Draw" << endl; }

string Triangle::GetIn fo(void)
{
string s;
char buff[200];
s = "Triangle - ";
sprintf(buff, "FillType: %d\n", fillType);
s += buff;
s += Shape::GetInfo( ).c_str();
return(s);
}

void Polygon::Draw(v oid)
{
cout << "Polygon Draw" << endl;
Triangle::Draw( );
}

string Polygon::GetInf o(void)
{
string s;
s = "Polygon - GetInfo";
s += Triangle::GetIn fo().c_str();
return(s);
}

//----------------------------------------------------------------------------------------------------------
// .cpp MAIN file
//----------------------------------------------------------------------------------------------------------
int sListSize = 0;

Shape *shapes[SIZE];

vector<Pointp1;
p1.push_back( Point(10, 10) );
p1.push_back( Point(100, 100) );
p1.push_back( Point(20, 20) );

shapes[0] = new Shape (p1);
shapes[1] = new Triangle (p1);
vector<Pointp2;
p2.push_back( Point(10, 10) );
p2.push_back( Point(100, 100) );
p2.push_back( Point(20, 20) );
p2.push_back( Point( 200, 200) );

//shapes[2] = new Polygon (p2);
shapes[2] = new Polygon (p2);

p2.push_back( Point(450, 120) );
shapes[3] = new Polygon (p2);
sListSize = 4;

cout << "\nDoing the old pointer list method: " << endl;
for(int i = 0; i < sListSize; i ++)
{
cout << "\n" << "I: " << i << " " << shapes[i]->GetInfo().c_st r() << endl;
shapes[i]->Draw();
}
cout << "\n--== DELETING MEMORY ==--\n";
cout << "Size: " << sListSize << endl;

for(int i = 0; i < sListSize; i ++)
{
cout << "DEL: " << i << endl;
delete shapes[i]; // --== This is causing me problems ==--
}
Apr 1 '07 #1
5 2111
* Renato:
I have an array of pointers to class Shape.

I create 4 items and display their values.

shapes[0 - 3]
This is not valid C++ syntax.

Shape *shapes[SIZE];

shapes[0] = new Shape (p1);
shapes[1] = new Triangle (p1);
shapes[2] = new Polygon (p2);

p2.push_back( Point( 210, 210) );
shapes[3] = new Polygon (p2);

sListSize = 4;

// --== This is what is causing my program to crash - but why? ==--
// Please help
for(int i = 0; i < sListSize; i ++)
delete shapes[i];
You need a virtual destructor.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Apr 1 '07 #2
I understand that shapes[0 - 3] is not correct C++ syntax, it was to show
the ascending progression of the assignments.

Shape *shapes[SIZE]; is declared within main.

Shape, Triangle and Polygon all have a standard destructor, there are no
pointers allocated within the classes, hence there was no need for an
explicit virtual destructor method. But I did provide one for both
Triangle and Polygon.

Please let me know if I am missing anything with these destructors.

I would like to clean up any memory allocations at the end of main.

Please provide some code for easier understanding if possible.

Regards
Renato

Alf P. Steinbach wrote:
* Renato:
>I have an array of pointers to class Shape.

I create 4 items and display their values.

shapes[0 - 3]

This is not valid C++ syntax.

>Shape *shapes[SIZE];

shapes[0] = new Shape (p1);
shapes[1] = new Triangle (p1);
shapes[2] = new Polygon (p2);

p2.push_back ( Point( 210, 210) );
shapes[3] = new Polygon (p2);

sListSize = 4;

// --== This is what is causing my program to crash - but why? ==--
// Please help
for(int i = 0; i < sListSize; i ++)
delete shapes[i];

You need a virtual destructor.

Apr 1 '07 #3
Alf P. Steinbach wrote:
>* Renato:
>>I have an array of pointers to class Shape.

I create 4 items and display their values.

shapes[0 - 3]

This is not valid C++ syntax.

>>Shape *shapes[SIZE];

shapes[0] = new Shape (p1);
shapes[1] = new Triangle (p1);
shapes[2] = new Polygon (p2);

p2.push_bac k( Point( 210, 210) );
shapes[3] = new Polygon (p2);

sListSize = 4;

// --== This is what is causing my program to crash - but why? ==--
// Please help
for(int i = 0; i < sListSize; i ++)
delete shapes[i];

You need a virtual destructor.
"Renato" <rk***@iinet.ne t.auwrote in message
news:46******** *************** @per-qv1-newsreader-01.iinet.net.au ...
>I understand that shapes[0 - 3] is not correct C++ syntax, it was to show
the ascending progression of the assignments.

Shape *shapes[SIZE]; is declared within main.

Shape, Triangle and Polygon all have a standard destructor, there are no
pointers allocated within the classes, hence there was no need for an
explicit virtual destructor method. But I did provide one for both
Triangle and Polygon.

Please let me know if I am missing anything with these destructors.

I would like to clean up any memory allocations at the end of main.

Please provide some code for easier understanding if possible.
Please don't top-post. Message rearranged.

Triangle has an int that shape does not have. It is posible that with this
included variable the compiler is rearranging in memory, for what ever
reason, the variables of Shape ( in this case two vectors). The destructor
for Shape has to destroy these vectors which is probably where your error is
coming it, because the compiler thinks it's a Shape, but it's actually a
Triange, so the memory layout has changed.

The short answer, if you use polymorphism, ALWAYS give a virtual destructor.

Even if you give NO custom destructors (comment them out for Shape, Tirangle
and Polygon) it still crashes. So you have to provide a virtual destructor.
Apr 1 '07 #4
On Apr 1, 2:44 pm, Renato <r...@iinet.net .auwrote:
I understand that shapes[0 - 3] is not correct C++ syntax, it was to show
the ascending progression of the assignments.
Shape *shapes[SIZE]; is declared within main.
Shape, Triangle and Polygon all have a standard destructor, there are no
pointers allocated within the classes, hence there was no need for an
explicit virtual destructor method. But I did provide one for both
Triangle and Polygon.
Shape is a base class. You delete via a Shape*. Thus, Shape
must have a virtual destructor, or the behavior is undefined.

--
James Kanze (Gabi Software) email: ja*********@gma il.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Apr 1 '07 #5
Renato wrote:
I understand that shapes[0 - 3] is not correct C++ syntax, it was to show
the ascending progression of the assignments.

Shape *shapes[SIZE]; is declared within main.

Shape, Triangle and Polygon all have a standard destructor, there are no
pointers allocated within the classes, hence there was no need for an
explicit virtual destructor method. But I did provide one for both
Triangle and Polygon.

Please let me know if I am missing anything with these destructors.

I would like to clean up any memory allocations at the end of main.

Please provide some code for easier understanding if possible.

Regards
Renato

Alf P. Steinbach wrote:
>* Renato:
>>I have an array of pointers to class Shape.

I create 4 items and display their values.

shapes[0 - 3]

This is not valid C++ syntax.

>>Shape *shapes[SIZE];

shapes[0] = new Shape (p1);
shapes[1] = new Triangle (p1);
shapes[2] = new Polygon (p2);

p2.push_bac k( Point( 210, 210) );
shapes[3] = new Polygon (p2);

sListSize = 4;

// --== This is what is causing my program to crash - but why? ==--
// Please help
for(int i = 0; i < sListSize; i ++)
delete shapes[i];

You need a virtual destructor.

Thank you to all who responded.

:)

Apr 1 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
5402
by: Ian McBride | last post by:
(was: delete() confusion) I have a class with multiple base classes. One of these base classes (base1) has its own new/delete operators and nothing else. Another base class (base 2) has a virtual destructor. The class with the virtual destructor has AddRef() and Release() methods, and Release() ultimately does a "delete this". Can that "delete this" statement somehow find the right delete method? If it does, it involves a downcast...
6
15723
by: Alexander Stippler | last post by:
Hi, I have some question about the usage of delete. I have some reference counted classes, all derived from SharedObject. It's destructor looks like this: ~SharedObject() { if (--references_ == 0) { delete this;
1
3844
by: Nimmi Srivastav | last post by:
There's a rather nondescript book called "Using Borland C++" by Lee and Mark Atkinson (Que Corporation) which presents an excellent discussion of overloaded new and delete operators. In fact there are quite a few things that I learned that I did not know before. For example, while I knew that the new and delete operators can be overloaded for classes, I did not know that that the global new and delete operators can also be overloaded. ...
5
5236
by: | last post by:
Hi all, I've been using C++ for quite a while now and I've come to the point where I need to overload new and delete inorder to track memory and probably some profiling stuff too. I know that discussions of new and delete is a pretty damn involved process but I'll try to stick to the main information I'm looking for currently. I've searched around for about the last too weeks and have read up on new and overloading it to some extent but...
2
2101
by: Pierre Phaneuf | last post by:
At my workplace, we are in the process of migrating to a component system similar to COM (but not COM itself, as we have some space and portability requirements) that uses refcounting for resource management. My problem is that I would like to find a way of finding out attempts to use "delete obj" when obj is a pointer to IUnknown or a derivative. Since this is a migration, we have a lot of existing code that uses delete directly, and I...
1
1482
by: Jeffro | last post by:
Hi, I am trying to create a form that would have only two buttons on it. When the user clicks on one of the buttons it will issue a prompt such as Do you wish to delete all records from the Classes Table? YES NO Upon clicking on yes, then all the records in the classes table would be deleted.
10
1463
by: n2xssvv g02gfr12930 | last post by:
In a job interview I was asked about the statement below: delete this; Naturally I was horrified, yet they claimed they had used it. Personally I'm pretty damn sure I could never justify this. So is this a case of Lord Bryon, "Mad, bad, and dangerous to know", or do you think you could ever justify using it? JB
12
2034
by: dennist685 | last post by:
Can't edit, delete or add row in an Access database in a website 2003 When I implement a walkthrough using Northwind I have no trouble doing this. Also, in a windowsforms project I have no problem editing, adding or deleting rows. But in webforms the smarttags don't offer the options. Can anybody help?
16
10330
by: Martin Vorbrodt | last post by:
some butthole asked me an interview question: can you delete "this" pointer in a member function of a class, like this: class C { public: void foo() { delete this; } }; my answer was... undefined behavior, maybe? object kills itself and frees
2
5477
by: shapper | last post by:
Hello, I have two tables: TagId, PostId TagId, PostId How can I delete, given a TagId, the record from Tags and all records associated with it in PostTags.
0
8462
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8382
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8893
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8802
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8586
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8658
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7405
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4206
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
2028
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.