I'm trying to understand inheritance in C++.
I want to dynamically create an array in a derived class and pass the array pointer to the base class, and then the base class fills in the array. Finally I want to print the array from the derived class.
I wrote the following code but when I run this, the program crashes and I get a segmentation fault error.
How should I implement this?!
class Base {
private:
int* array;
public:
Base(int* a) {
array = a;
for(int i = 0 ; i < 10 ; i++) {
array[i] = i;
}
}
};
class Child : public Base {
private:
int* array;
public:
Child() : array(new int[10]), Base(array) {}
void print() {
for(int i = 0 ; i < 10 ; i++) {
cout << array[i] << endl;
}
}
};
array?i want to new an arrayDon't. Pretty please with a dollop of ice cream and a cherry on top don't. Arrays are bad for you. Arrays cause plaque in your teeth and early onset of Alzheimer's.newis responsible for global warming and vegan zombie apocalypsis due any day now. Usestd::vector, a healthy, environment-friendly, GMO-free choice of the no-newgeneration.