tags:

views:

73

answers:

1

i have 3 classes A,B and C. C is derived from A and B. i get pointer to pointer of class C and cast to A** , and B ** , the variable that hold the the B** has the address of A** in my example B ** BdoublePtr hold the address of A** .i am using the following code

#include "conio.h" 
#include "stdio.h"
#include "string.h"

class A
{
public:
    A()
    {
        strA=new char[30];
        strcpy(strA,"class A");
    }
    char *strA;
};


class B 
{
public:
    B()
    {
        strB=new char[30];
        strcpy(strB,"class B");
    }
    char *strB;
};

class C : public A, public B
{
public:
    C()
    {
        strC=new char[30];
        strcpy(strC,"class C");
    }
    char *strC;
};

int main(void)
{
    C* ptrC=new C(); 
    A * Aptr=(A*)ptrC; 
    printf("\n class A value : %s",Aptr->strA); 

    B * Bptr=(B*)ptrC;
    printf("\n class B value :%s",Bptr->strB);

    printf("\n\nnow with double pointer ");
    A ** AdoublePtr=(A **)&ptrC;
    Aptr=*AdoublePtr;
    printf("\n class A value : %s",Aptr->strA);

    B * * BdoublePtr=(B ** )&ptrC;
    Bptr=* BdoublePtr;
    printf("\n class B value : %s",Bptr->strB);

    getch();
    return 0;
}
+2  A: 

The problem is that what you are trying to do is impossible; there is no valid conversion from C** to B**. The pointer at *BdoublePtr contains the address of a C, not a B, and nothing you do to BdoublePtr can change that.

The C-style cast in your code is equivalent to a reinterpret_cast; it takes the value of the C* and pretends it's a B*. This gives undefined behaviour. In your case, Bptr->strB happens to find the string in the A object in the C object that the pointer points to, but in principle absolutely anything could happen.

By the way, if you're writing C++, then you really should use C++ headers and strings. That would fix some of the memory leaks in your code for a start.

Mike Seymour