Finish. Thanks everyone
Printable View
Finish. Thanks everyone
This sounds like homework.
One of the "Effective" series covers this specific problem in an Item, but I can't recall which one. Probably Effective C++. The item would be called something like "Don't use polymorphic arrays".
A few clues....
array[i] = *(array + i)
try sending an array of derived to a function expecting an array of base. What happens? Can you work out why?
Unfortunately, we can't really give you a hint as to why the behavior is bad without actually telling you. Try this
Create an array of A and an array of class B, look carefully at the memory. Why you can't do that should become obvious.Code:class A {
public:
A(){i = 0;}
int i;
};
class B : A {
public:
B(){j = 0xFFFFFFFF;}
unsigned int j;
};
Sorry, I forgot posting my solution. Any comments for me?Code:#include <iostream.h>
class B {
public:
char dataB;
B(char x) {
dataB=x;
}
void showB() {
cout << dataB;
}
};
class D: public B {
public:
char dataD;
char dataX;
D(char x, char y):B(x) {
dataD=y;
}
void show() {cout << dataB << " " << dataD <<'\n';}
};
void process(B* p) {
p->dataB='Z';
}
void process(B* a, int n) {
a[1].dataB='H';
}
int main() {
int n=2;
D ob[]={D('B','D'),D('P','Q')};
//process(ob+1);
process(ob,n);
for (int i=0;i<n;i++) {
ob[i].show();
}
return 0;
}
Does someone have some hints for me?
Thanks very much!
iostream.h is very very deprecated. The correct header is <iostream>
We can see whats happening in your code, but your mission is to explain why and we do not see any explanation for the exhibited behaviour.
I wrote some code that shows you the behavior you are talking about, do you see why the output is the way that it is?
Code:#include <iostream>
class A {
public:
A(){i = 0;}
unsigned int i;
};
class B : public A {
public:
B(){j = 0xFFFFFFFF;}
unsigned int j;
};
static void printA(A * array, size_t len){
for(size_t k = 0; k < len; ++k, ++array){
std::cout << (*array).i << std::endl;
}
}
static void printB(B * array, size_t len){
for(size_t k = 0; k < len; ++k, ++array){
std::cout << (*array).i << std::endl;
}
}
int main(void){
B testArray[10];
printA((A*)testArray, 10);
printB(testArray, 10);
return 0;
}
1) What is an array? Given that, how does the compiler know where each array element starts? For example, if you have an array of Base, and Base[0] is the first element in memory, how does the compiler know where Base[1] is in memory, Base[2], Base[3], etc.? Please explain this.
2) Given your answer for 1) above, if the compiler expects an array of Base, but the array has actually an array of Derived objects (where Derived is derived from Base), and that Derived objects are larger in size than Base objects (a huge clue), what do you think the compiler will do, given your answer above?
That, in a nutshell, is your answer.
Regards,
Paul McKenzie