Hi! The overall logic is that u should know the actual memory location where the data is to be stored or have a reference to it,in ur case a *a1 it is just a pointer variable . and this pointer is not pointing to the location where the new object would be allocated,so it is passed just as a pointer variable to the function f(a *b) where this variable is overwritten by the ,actual address where the object is being allocated through new a().
and in ur main ,the value of the pointer variable is still not known,it just random ,that's why u are getting output as something garbage. passing the address of the pointer is allready being discussed, but in other method u can just pass the address of the new object to the calling function that will tell ur main(),that what is the actual location of the object;and this time it is not garbage. a* f(a * b) { b = new a(); b->set(5); return b; } int main() { a *a1; a1=f(a1); cout<<"x = "<<a1->get(); return 0; } On Jul 21, 5:10 pm, Saurabh <saurabh24...@gmail.com> wrote: > Can any one explain why the following program not giving the correct output. > > #include <iostream> > using namespace std; > class a > { > int x; > > public: > void set(int y) > { > x=y; > } > int get() > { > return x; > } > > }; > > void f(a * b) > { > b = new a(); > b->set(5);} > > int main() > { > a *a1; > f(a1); > cout<<"x = "<<a1->get(); > return 0; > > } > > -- > Regards > Saurabh -- You received this message because you are subscribed to the Google Groups "Algorithm Geeks" group. To post to this group, send email to algogeeks@googlegroups.com. To unsubscribe from this group, send email to algogeeks+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/algogeeks?hl=en.