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;
 }

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Note that this was already answered here: stackoverflow.com/questions/7196172/…
Thanks! I will try it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.