0

Am I allowed to do the following? To initialize a base class pointer with an array of derived class objects? The gnu g++ it is crashing when reaching the delete statement ...

Any suggestion? Do I have to overload the new [] and delete operators?

Thanks!

   #include <iostream>

   using std::endl;
   using std::cout;
   using std::cin;

   // base class --> Base

   class Base {
   public:

   // constructor

   Base() {
       cout << " --> constructor --> Base" << endl;
   }

   // destructor

   virtual ~Base() {
       cout << " --> destructor --> ~Base" << endl;
   }
 };

 // derived class --> D1

 class D1 : virtual public Base {
 public:

 // constructor

 D1() : Base(), x1(10) {
      cout << " --> constructor --> D1" << endl;
 }

 // destructor

 virtual ~D1() {
      cout << " --> destructor --> ~D1" << endl;
 }

 private:

 int x1;   
 };

 // the main program

 int main()
 {
    const int DIM = 100;
    Base * pb2 = new D1 [DIM];
    delete [] pb2;

    return 0;
 }
paulsepolia
  • 35
  • 1
  • 9

1 Answers1

1

This will not work - C arrays do not know about the dynamic size of polymorphic types. If you want to use polymorphism, then you have to use arrays (preferably std::vector or another standard array, not a C array) of pointers (preferably smart pointers) to the base type.

sfjac
  • 7,119
  • 5
  • 45
  • 69