Ananth wrote:
> 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
Hmm...interesting and I can see why it might fail. But this should work:
int main()
{
Base *ptrBase = new Derv;
delete ptrBase;
return 0;
}
To do an array of base, you have to be a bit more creative: SmartPtr<>
with a Clone()/Copy() and have a Clone()/Copy() with a variant return
type in both the base and derived classes and then use a Block<
SmartPtr<Base> > as the wrapper. That should work on every modern
compiler (assuming it supports variant return types).
--
Thomas Hruska
CubicleSoft President
Ph: 517-803-4197
*NEW* MyTaskFocus 1.1
Get on task. Stay on task.
http://www.CubicleSoft.com/MyTaskFocus/