Question

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?

Was it helpful?

Solution

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)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top