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++?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With