Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How initialize array and pass a pointer it to base constructor from derived?

Rewrote the question completely. Please, read it carefully

Single note to not confuse you: Base constructor expects pointer to constants array. It doesn't store a pointer itself, it stores the data!

I have the following code:

class Base {
public:
    Base(int*);
    // added this to explain why I need inheritance
    virtual void abstractMethod() = 0;
};

Base::Base(const int *array) {
    // just for example
    cout << array[0] << endl;
    cout << array[1] << endl;
    cout << array[2] << endl;
}

class Derived : private Base {
public:
    Derived();
    void abstractMethod();
};

// who will delete? how to initialize?
Derived::Derived(): Base(new int[3]) {
}

I want to hide Base(int*) constructor from the user of my Derived class. To do that I need to supply default values to that array.

The problem is that when I use initialization list like this:

Derived::Derived(): Base(new int[3]) {
}

array is not initialized and Base constructor prints some garbage. Another problem with this code: who will free that new array?

How to initialize array before it is passed to Base class? Is it possible at all in C++?

like image 597
Vanuan Avatar asked Feb 03 '11 09:02

Vanuan


1 Answers

Short answer: you can't (unless you are willing to rely on possible quirks in a particular compiler). For standard compliance, Base must be fully constructed before anything else in Derived can be safely touched.

Focus instead of what you are trying to achieve. Why must the array be in Derived; why do you feel a need to let Base initialize? There are probably dozens of safe ways of achieving what you need.

like image 104
Pontus Gagge Avatar answered Oct 01 '22 20:10

Pontus Gagge