▲ 0 r/cpp_questions
I have myself a base class and derived class. The derived class has I make an array of pointers to the base class and I want to loop through the array and use the function for the derived class. Here is sample code:
#include <iostream>
using namespace std;
class Base {
protected:
int num1;
public:
void SetData() {
cout << "number: "; cin >> num1;
}
void DisplayData() {
cout << "number: " << num1 << endl;
}
};
class derived : public Base {
int num2;
public:
void SetData() {
Base::SetData();
cout << "number2: "; cin >> num2;
}
void DisplayData() {
Base::DisplayData();
cout << "number2: " << num2;
}
int Sum() {
return num1 + num2;
}
};
int main() {
Base* arr[4];
for (int i = 0; i < 4; i++) {
// use the function Sum from the derived class
arr[i].Sum(); // this is not working :(
}
return 0;
}
u/I_Am_The_DM_ — 13 days ago