I have an array of size MAX of class pointers.
How can I define a pointer to the same, and access member functions of base, derived, etc?
class base
{
public :
base() {cout << "base class constructor" << endl;}
virtual void g() {cout << "base :: g()" << endl;}
};
class derived_1 : public base
{
public :
derived_1() : base() {cout << "derived_1 class constructor" << endl;}
virtual void g() {cout << "derived_1 :: g()" << endl;}
};
class derived_2 : public derived_1
{
public :
derived_2() : derived_1() { cout << "derived_2 class constructor" << endl;}
void g(int) {cout << "derived_2 :: g()" << endl;}
};
int main()
{
int i;
base b;
derived_1 d_1;
derived_2 d_2;
base* arr[MAX] = {&b, &d_1, &d_2};
base *(*pArr)[MAX];
pArr = arr;
for (i=0 ; i < MAX ; i++)
{
pArr[i]->g();
}
return 0;
}
I get a compilation error:
error: cannot convert 'base* [3]' to 'base* (*)[3]' in assignment
When I change it to below, it works, however it looks more like a hack to me, and method 1 looks more formal to me:
base* arr[3] = {&b, &d_1, &d_2};
base **pArr;
pArr = arr;
for (i=0 ; i < 3 ; i++)
{
pArr[i]->g();
}
arris a pointer ofMAXpointers tobase.pArris a pointer to such array, you cannot simply assign one to the other.&is the address of operator.int x = 42; int * p = x;wont compilepArrpArr[i]->g();is totally wrong. You wantarr[i]->g()