Accessing members from a shared pointer passed as argument to a function gives incorrect results without typecast

Hi, class A; class B; typedef boost::shared_ptr<A> pSharedPtrA; typedef boost::shared_ptr<B> pSharedPtrB; class B { public: int memberB; }; Class A { public: pSharedPtrB pMember; }; Suppose i have one shared pointer of type pSharedPtrA pointing to an object of class A and the member variable pMember pinging to a valid object of class B. Now if i pass the shared pointer of type pSharedPtrA to a function suppose Test_Func(pSharedPtrA): void Test_Func(pSharedPtrA pLocalA) { pSharedPtrA ptrA = boost::static_pointer_cast<A> (pLocalA) pSharedPtrB tmpB = boost::static_pointer_cast<B>(ptrA->pMember) Another_Func(tmpB) } Another_Func(pSharedPtrB pLocalB) { int x = pLocalB->memberB; //Gives WRONG value pSharedPtrB ptmp = boost::static_pointer_cast<B> (pLocalB) x = ptmp ->memberB; //Gives CORRECT Value } The problem is when typecast is not used then in function Another_Func(pSharedPtrB pLocalB), pLocalB->memberB is not giving the correct result but after typecast it is giving the correct results. The inference is that in function Another_Func() data is preserved in the pLocalB but without typecast i am not able to access it. Though i have not declared any virtual functions in above code but where we are having problem does contain the vritual functions. I dont know if it has any bearing on behavior observed. I want to know why typecasting is required to get the correct result and why cant i access the members without typecasting. Thanks and Regards Deepak

On 4/15/2013 6:02 AM, Deepak Gunjal wrote:
Hi,
class A; class B; typedef boost::shared_ptr<A> pSharedPtrA; typedef boost::shared_ptr<B> pSharedPtrB;
class B { public: int memberB; };
Class A {
public:
pSharedPtrB pMember;
};
Suppose i have one shared pointer of type pSharedPtrA pointing to an object of class A and the member variable pMember pinging to a valid object of class B.
Now if i pass the shared pointer of type pSharedPtrA to a function suppose Test_Func(pSharedPtrA): void Test_Func(pSharedPtrA pLocalA) { pSharedPtrA ptrA = boost::static_pointer_cast<A> (pLocalA)
pSharedPtrB tmpB = boost::static_pointer_cast<B>(ptrA->pMember)
Another_Func(tmpB) }
Another_Func(pSharedPtrB pLocalB) { int x = pLocalB->memberB; //Gives WRONG value pSharedPtrB ptmp = boost::static_pointer_cast<B> (pLocalB) x = ptmp ->memberB; //Gives CORRECT Value
}
The problem is when typecast is not used then in function Another_Func(pSharedPtrB pLocalB), pLocalB->memberB is not giving the correct result but after typecast it is giving the correct results.
In the code above memberB is never initialized, so how do you know what is the correct value? Provide a minimal fully compiling, runnable example. Doing so will probably uncover your problem, and at least will allow others to run your example. Jeff
participants (2)
-
Deepak Gunjal
-
Jeff Flinn