views:

70

answers:

1

Say I have some structs like this:

struct A{
 int someInt;
}

struct B : public A{
 int someInt;
 int someOtherInt;
}

And a class:

class C{
 A *someAs;
 void myFunc(A *someMoreAs){
  delete [] someMoreAs;
 }
}

would this cause a problem:

B *b=new B[10];
C c;
c.myFunc(b);

Because it's deleting b, thinking that it's of type A, which is smaller. Would this cause a memory leak?

Also, say I want to allocate more of the same as b within myFunc, using new, but without C knowing whether b is of A or B? A friend sugegsted typeof, but VC doesn't seem to support this.

+4  A: 

No memory will leak in this particular case because both A and B are POD (plain old data) and thus their contents do not require any destruction.

Still, it is a good practice to always have a virtual destructor in a (base) class that is supposed to be inherited from. If you add a virtual destructor to A, any deletion via A* will call the proper derived destructors too (including destruction of derived classes' members).

virtual ~A() {}

Notice, however, that you cannot use inheritance in arrays of base type, precisely because the actual size of the objects might differ.

What you really want is probably an array of pointers to base class:

std::vector<A*> someAs;

Or the Boost equivalent (with automatic memory management and nicer API):

boost::ptr_vector<A> someAs;
Tronic