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?

7
  • You mean it prints "enter the id" and then after you enter an ID it doesn't continue? Commented Dec 21, 2013 at 13:57
  • 1
    All of the pointers in a are uninitialized when you initialize a2 with them. Commented Dec 21, 2013 at 13:58
  • Your formatting / indentation could use some work. Commented Dec 21, 2013 at 13:59
  • @sftrabbit Yes , i did the cout and cin for the others (first name , last name ) but it didn't show up , and the program stop running Commented Dec 21, 2013 at 13:59
  • 1
    You do know about std::vector? Commented Dec 21, 2013 at 13:59

1 Answer 1

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)

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

4 Comments

I use the dynamically allocating because of the phone_number , i couldn't reach it without dynamically allocating !
@RaiOu It looks more like you use dynamic allocation because you don't know how to use standard library containers.
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.
@GabrielL. that would lead to undefined behaviour, because A has no virtual destructor :-)

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.