Possible Duplicate:
C++ – when should I use a pointer member in a class
I’ve worked with c++ for years but I still have questions I havent answered..
I am defining a c++ class but I have some doubts about this
question 1: should I store investment by using pointer or no?
Investment* investment;
// or
Investment investment;
question 2: why?
question 3: in case I use Investment investment; should I return a reference this way Investment & getInvestment();?
I know that both ways my code works but I would like to know the efficient way to do this..
the code follows:
class Urgency
{
private:
Investment* investment;
public:
Urgency(Investment* investment);
~Urgency(void);
Investment* getInvestment();
};
I typically prefer to use pointer when the object is large and to use a stack object when it is small. Pointers allow for some things such as lazy init and forward declaration, while stack objects reduce the likely hood you’ll need to create your own copy constructor and having to worry about explicitly destroying the object in the destructor. (although, you could use a shared pointer type object to do this for you) Also, a stack object is typically faster to access, but in most scenarios this shouldn’t be a reason for choosing one over the other as the difference in most applications is negligible.
In reference to your code, you typically would return a
const Investment &in order to not allow direct modifications to Investment object. As mentioned above, if you use a raw pointer, you should create a copy constructor and a destructor that properly manage the memory on the object. With a pointer object you would typically return aconst Investment *again to remove the ability for an outside caller to directly modify your object.Take notice of how your functions are declared in the Investment class when you return const correct Investment objects. If you simply have
Investment::getNumShares(), you will not be able to access the function using a const reference or const pointer. To fix this issue, mark all member functions that do not modify the object to be const such asInvestment::getNumShares() const