Thomas Hruska <[EMAIL PROTECTED]> wrote:
> Ananth wrote:
> > Scott Meyers (and the standard) clearly instruct not to treat arrays
> > polymorphically in C++.
> > Because compiler has no means of finding out whether heap objects
> > pointed by base class pointers are base class objects or derived class
> > objects. Program will bomb when deleting array of base class pointers
> > pointing to derived class objects.
>
> I'm not sure I understand what you are getting at (and Google wasn't too
> helpful either). Got some example code?
Following code is supposed to bomb when compiled in g++ , intel c++
compiler (icc) and Poertlan Group C++ compiler (pgCC).
I say supposed to because I do not have any of these compilers, I'm
borrowing this information from codeguru forum and couple of other
sites.
CodeGuru forum had this useful output information when using one of
the above compilers, when the actual deletion of array objects happen
:
"C++ runtime abort: freeing array not allocated by an array new operation
Abort (core dumped)"
class Base
{
public:
virtual ~Base() {}
Base() { }
private:
int m_i;
};
class Derv: public Base
{
public:
virtual ~Derv() {}
Derv() { }
private:
int m_b;
char m_ch;
};
void freemem(Base ptrBase[])
{
delete []ptrBase; //code tries to delete array of Base objects,
not derived objects in some (many?) compilers. Warned by Scott Meyers
}
int main( )
{
Base *ptrBase = new Derv[10];
freemem(ptrBase);
return 0;
}
But it works perfectly well in MSVC. So MSVC somehow knows array of
base class pointers is actually pointing to derived objects.
Something that g++ , intel c++ compiler (icc) and Poertlan Group C++
compiler (pgCC) do not know and that is why program crashes in these
compilers.
Cheers
- Ananth