I’m coming (very recently) from C#, where I am used to instantiating objects like this:
Phone myPhone = new Phone();
simply writing
Phone myPhone;
essentially creates a holder for a class, but it is yet to be initialised so to speak.
now I’m writing a small class in C++ and I have a problem. Here is the pseudo code:
Phone myPhone;
void Initialise()
{
myPhone = new Phone();
}
void DoStuff()
{
myPhone.RingaDingDong();
{
In fact this is a little misleading as the above code is what I would LIKE to have, because I want to be able to put all my initialisation code for lots of things into one neat place. My problem is that the line inside initialise is unnecessary in C++, because before that, a new instance is already created and initialised by the very first line. On the other hand if I put the just the first line inside Initialise() I can no longer access it in DoStuff. It is out of scope, (not to mention the differences between using ‘new’ or not in C++). How can you create simply a holder for a class variable so I can initialise it in one place, and access it in another? Or am I getting something fundamentally wrong?
Thanks in advance!
If your Phone constructor takes no parameters then your life is pretty simple – you don’t need to new up the phone in the Initialize method. It will be created for you when the object is created and the lifetime will be managed for you.
If you need to get parameters to it, and it doesn’t have an Initialize() method or some set methods, then you may need to use a pointer (which can sometimes be null) and have Initialize() call new and pass in those parameters. Your other code needs to check if the pointer is null before using it. Also you need to manage lifetime (by writing the big 3) or use a smart pointer such as shared_ptr from C++11. This should not be your first choice.