I have a simple question about instantiating an object in C++:
If we assume that my class has a default constructor, then I create the new object like that:
PfAlgorithm object = new PfAlgorithm();
but when I run I get this error:
conversion from ‘PfAlgorithm*’ to non-scalar type ‘ns3::PfAlgorithm’ requested
Can someone explain to me the reason of this error please?
Thank you very much.
The
newoperator returns a pointer, not a value. So you need to write:Where
objectis a pointer to the newly allocated PfAlgorithm object. Some simple introductory information about pointers can be found here. However as has been discussed in the comments below, it is almost never a good idea to deal in raw pointers (due to potential issues with memory leaks, issues of ambiguous ownership etc). Read on…Having allocated this object on the heap, you need to make sure you delete it when you’re finished with it, otherwise your application will leak memory. In order to make this easier I strongly recoomend you also consider using smart pointers from the boost libraries (or from C++11) to manage your memory.
Alternatively, as various others have suggested, you can simply do:
And allocate your object on the stack and not have to worry about managing the memory.