There are two things wrong with your code, that need to be fixed before answering the question.
- The fact that those global pointers are global - having something global, at global namespace, is sign of bad design (if your teacher is advocating it - because it seems kinda like homework - then slap him in the face for doing so).
- The fact that those global pointers are raw pointers - you either want to keep the ownership in their place and not pass the ownership around - then you'll use either
unique_ptr or just plain object (unless the object is supposed to live longer than main(), but that's a weird case).
So, after correcting the code, it looks like this:
int main() { A a; A b(a); }
If you need to access those objects from other parts of the code, without explicitly passing them around, put them in sensibly named namespace:
// in header namespace a_and_b // this is *wrong* name for it, of course { extern A a; extern A b; } // in one of TUs - also possible to wrap this in namespace ... { ... } A a_and_b::a; A a_and_b::b(a_and_b::a);
Of course, if you are just asking for syntax, the answer would be:
A * b = new A(*a);
so just dereference the pointer to get A out of A *. But please, don't ever do this - even in freestanding environment you can easily implement own smart pointer to wrap this in sane way.