My program allocated an array of class "CB" (CB* pB = new CB[3], and then, "pB" will be post to a method as a parameter (void test( CA* pA, int num)). CA is the superclass of CB. So, in function "test", pA will be used as an array for CA. In this case, how can I upcast successfully? The following program would only upcast the first element of pB to class "CA", from the 2nd element of array, I got the wrong result... Is there anyone could help me? thx!!!!
Code:
class CA {
public:
void setA( int num ) { a = num; }
void doSth() {
printf( "A is: %d\n", a );
}
CA() { a = 0; };
private:
int a;
};
class CB : public CA {
public:
void setB( int num ) { b = num; }
void doSth() {
printf( "B is: %d\n", b );
}
CB() { b = 0; };
private:
int b;
};
void test( CA* pA, int num )
{
for( int i=0; i<num; i++ ) {
pA[i].doSth();
}
}
int main(int argc, char* argv[])
{
CB* pB = new CB[3];
pB[0].setA(1);
pB[1].setA(2);
pB[2].setA(3);
test( dynamic_cast<CA*> (pB), 3 );
int nTest;
nTest = getchar();
return 0;
}