Tuesday, July 14, 2009

Can address(&) be used as a pointer in c ?

We have always assigned(stored) the address of a datatype in a special variable called pointer, and then used the pointer which points to the datatype to carry out various operations. Can anybody tell me if there is a way which allows instead of storing the address in a pointer variable, whether the address of the datatype can be directly used(like a pointer) to carry out the operations on the dataype. For example, let's take the small example :





# include %26lt;iostream.h%26gt;


# include %26lt;conio.h%26gt;





struct A


{


virtual void f()


{cout %26lt;%26lt; "Class A" %26lt;%26lt; endl;}


};





struct B:A


{


void f()


{cout %26lt;%26lt; "Class B" %26lt;%26lt; endl;}


};





int main()


{


A a;


B b;


A *ptr;


clrscr();


ptr = %26amp;a;


// My question is whether f() could be accessed somehow by using %26amp;a instead


// of using the ptr as done below


ptr -%26gt; f();


cout %26lt;%26lt; endl;


ptr = %26amp;b;


// same question for the below operation


ptr -%26gt; f();


getch();


}





I have included my question inside the code, please help

Can address(%26amp;) be used as a pointer in c ?
Yes and sort of...





By wrapping in parens, you force the expression (%26amp;a) to be resolved first, the type of the expression should be imputed as (A*), so after the first assignment of ptr, these:





(%26amp;a)-%26gt;f();


ptr-%26gt;f();





should be equivilent. However, b is (obviously) of type B, so the type of (%26amp;b) should be imputed as (B*), whereas ptr is type (A*). As such, to get the equivilent of the second assignment of ptr (without assigning a pointer) you need a type cast to override the imputed type, e.g.,





(A*)(%26amp;b)-%26gt;f();








Make sense?
Reply:Sure.





A a;


B b;


A *aa = new A();


B *bb = new B();





a.f(); /*prints Class A*/


b.f(); /* prints Calls B */


aa-%26gt;f(); /*prints Class A*/


bb-%26gt;f(); /* prints Calls B */





// playing with v-tables


b.A::f(); /* prints Class A, uses the B object data with the logic from A's f() */


bb-%26gt;A::f() /* prints Class A, uses the B object data with the logic from A's f() */
Reply:Absolutely yes. You can.


No comments:

Post a Comment