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".
try sending an array of derived to a function expecting an array of base. What happens? Can you work out why?
Get Microsoft Visual C++ Express here or CodeBlocks here.
Get STLFilt here to radically improve error messages when using the STL.
Get these two can't live without C++ libraries, BOOST here and Loki here.
Check your code with the Comeau Compiler and FlexeLint for standards compliance and some subtle errors.
Always use [code] code tags [/code] to make code legible and preserve indentation.
Do not ask for help writing destructive software such as viruses, gamehacks, keyloggers and the suchlike.
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.
Get Microsoft Visual C++ Express here or CodeBlocks here.
Get STLFilt here to radically improve error messages when using the STL.
Get these two can't live without C++ libraries, BOOST here and Loki here.
Check your code with the Comeau Compiler and FlexeLint for standards compliance and some subtle errors.
Always use [code] code tags [/code] to make code legible and preserve indentation.
Do not ask for help writing destructive software such as viruses, gamehacks, keyloggers and the suchlike.
#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;
}
Sorry, I forgot posting my solution. Any comments for me?
Does someone have some hints for me?
Thanks very much!
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
Last edited by Paul McKenzie; November 22nd, 2010 at 06:37 PM.
Bookmarks