Re: I don't get it
Bharath wrote:
On Jun 18, 11:17 am, Jo <jo.lan...@telenet.be> wrote:
class A {
public:
char text_a[100];
A() { *text_a=0; }
~A() {}};
//-----------------------------------------------------------------------------
class B {
public:
char text_b[100];
B() { *text_b=0; }
~B() {}};
//-----------------------------------------------------------------------------
class C : public A, public B {
public:
char text_c[100];
C() { *text_c=0; }
~C() {}};
//-------------------------------------------------------------------------------
void test() {
B *bp1,*bp2;
C c,*cp1,*cp2,*cp3;
void *p;
strcpy(c.text_a,"hello a");
strcpy(c.text_b,"hello b");
strcpy(c.text_c,"hello c");
cp1=&c;
p=cp1;
bp1=cp1; // ok
bp2=(B*)p; // resulting bp2 is WRONG!
cp2=(C*)p; // ok
cp3=(C*)bp2; // resulting cp3 is WRONG! Which is logical because bp2
is already wrong.}
//-----------------------------------------------------------------------------
So the hot spot is the bp2=(B*)p;
What's wrong with that???
I can imagine someone saying "p is not pointing to a B object".
But if you think about it, conceptually, it does, imho.
So is it more a technical matter of compiling this!?
Maybe i'm stupid and/or missing something essential about C++.
If so, please give me a link to where i can study this right.
Cheers,
Jo
I re-wrote your test function like this -
int main() {
B *bp1,*bp2;
C c,*cp1;
void *p;
int a;
strcpy(c.text_a,"hello a");
strcpy(c.text_b,"hello b");
strcpy(c.text_c,"hello c");
cp1=&c;
p=cp1;
bp2=(B*)p;
std::cout<<p<<"\n";
std::cout<<bp2;
std::cin>>a;
}
I printed the value in p and also in bp2. Both are one and the same.
On my m/c the O/P was -
0x22fe28
0x22fe28
Why do you think, in your program, resulting bp2 is WRONG?
Because i got runtime problems.
So i narrowed down everything to the above code.
Running this on my PC gives a wrong bp2 pointer. I can see it in the
"Watch" panel.
And i also did a similar thing than you: at the end of the test/main
function i did a
OutputDebugString(cp3->text_a);
OutputDebugString(cp3->text_b);
OutputDebugString(cp3->text_c);
This gives rubbish for text a!!!
Compilation is done with Visual C++ 7.1.3088