0

I want to initialize an array. There's no compilation error but when I run the program it shows the first cout then stop running.

Here's my code:

class A {
    string first_name ;
    string last_name;
    int ID;
public:
    virtual void print ()=0;
};

class B :public A{
    string phone_number;

    .......
    void print(){
        ........
    }
};

class D{
    A** a;
    int size;
public:
    D(){
        size = 10;
        a = new A *[size];
        for(int i = 0 ; i<size ; i++){
            a[i] = NULL;
        }
    }

    void Add(){
        for(int i = 0 ; i<size ; i++){
            A * a2 = a[i];
            B * b  = dynamic_cast<B*>(a2);
            int id;
            cout<<"enter the id";
            cin>>id
            b->set_ID(id);
            // i did the same (cout , cin statements) for the first name and last name.
            b->set_first_name();
            b->last_name();
        }
};

Is this not correct?

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Rai Ou
  • 15
  • 6

1 Answers1

1

You allocate size amount of A*s, but you don't actually make those pointers point anywhere. They're uninitialized. Edit: now you're just setting them to NULL. You would need to allocate some A objects and assign their addresses to each of the elements of a. However, I see no good reason for you to be dynamically allocating the array of pointers - why don't you just declare a as A* a[10];? (or better yet, use a std::vector or std::array)

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
  • I use the dynamically allocating because of the phone_number , i couldn't reach it without dynamically allocating ! – Rai Ou Dec 21 '13 at 14:03
  • 2
    @RaiOu It looks more like you use dynamic allocation because you don't know how to use standard library containers. – juanchopanza Dec 21 '13 at 14:05
  • 2
    Just a side remark : he never deallocate his `A` objects. That's a problem when allocating objects, it's easy to forget to deallocate them. – Gabriel L. Dec 21 '13 at 14:10
  • 1
    @GabrielL. that would lead to undefined behaviour, because `A` has no virtual destructor :-) – juanchopanza Dec 21 '13 at 14:16