1

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();
};
Community
  • 1
  • 1
thiagoh
  • 7,098
  • 8
  • 51
  • 77
  • 1
    @jogojapan i'd already seen this question but I have another questions about this that is not answered.. see question 2 and 3.. thanks – thiagoh Nov 13 '12 at 04:29
  • 1
    I believe question 2 ("why?") is answered by the duplicate question, although on a very general level. If you need a more specific answer, you'll have to provide more details of what the `Investment` class is and does, and how you use it. Question 3 might actually justify an entirely separate post (and I wouldn't be surprised if there were duplicates for that too). – jogojapan Nov 13 '12 at 04:33
  • 1
    @jogojapan sorry but I disagree with you.. I prepared a question which in my opinion can clarify these doubts in a more entire way.. – thiagoh Nov 13 '12 at 06:17

5 Answers5

3

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 a const 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 as Investment::getNumShares() const

RC.
  • 27,409
  • 9
  • 73
  • 93
1
  1. don't use pointers, unless you absolutely need them
  2. because they are prone to errors when not used very carefully
  3. better yet, return const & if you don't plan to let everybody to do changes in your Investment
lenik
  • 23,228
  • 4
  • 34
  • 43
1

question 1/2: should I store investment by using pointer or no? / why?

Investment* investment;
// or
Investment investment;

There are pros and cons to each.

Not using a pointer:

  • Saves you the trouble of worrying about creating and deleting the Investment object - though you can explicitly select an Investment constructor in your initialisation list if useful.
  • Means the Investment object is allocated within the host object, which can save a heap allocation and deallocation. That may be more memory efficient and perform better.

Using a pointer:

  • Allows you to use lazy initialisation: you can defer creating the Investment object until the containing object actually needs it, then possibly delete it again when no longer needed. This manual control of lifetime can be used to fine-tune memory usage. Storing NULL/0 in the pointer when it doesn't point to an actual Investment is a common practice to help track this.
  • Means you can give ownership of the Investment object to code outside your object... they can keep using it and delete it when appropriate.
  • Means you have to carefully craft a copy constructor, and carefully handle exceptions in your constructor. Smart pointers may be able to help with these things.
  • Means you can allocate an instance of a class derived from Investment, and use it through the same pointer. This allows you to choose a custom implementation suited to your run-time needs, or even to vary the implementation as the needs vary. This flexibility is a cornerstone of Object Oriented programming and run-time polymorphism.
  • Means the header for your containing object only needs to see (whether by #include or in the same file) a forward declaration of the Investment class. This means changes can be made to the Investment object without forcing a recompilation of code that only uses the containing object (just a relink of the object containing the modified Investment implementation will be required). The concept is the same as the pointer-to-implementation or pImpl idiom, though the Investment isn't necessarily a dedicated part of the implementation of the containing class, and may be used directly and independently elsewhere in your program.

question 3: in case I use Investment investment; should I return a reference this way Investment & getInvestment();?

That depends a lot on the program. Sometimes it's best to avoid exposing a data member directly, and instead provide a higher level logical function in the containing object that does some work on the Investment: that way you can maintain extra invariants around the Investment object - i.e. you can control, coordinate and monitor when and how it's used. Other times it may just be more practical to expose it.

Returning a reference is only appropriate if you can be certain you'll actually have an Investment object to return: in your pointer version, the implementation may need to create/new an Investment object if it doesn't already have one. Alternatively, returning a pointer means you can return NULL/0 to the client code to indicate that you don't have an Investment object yet, but then you have to ensure your class and the client code understand who'll have ongoing ownership (i.e. the right/obligation to delete the Investment object), and that neither side will be trying to use the Investment after the other side's deleted it.

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
0
  • By using pointers you can choose when to allocate the memory and also delete it, while the normal declaration has automatic storage. To answer the question, it really depends on the type of program you're writing and personal preference.

    class Foo
    {
        Foo* Obj; //choose when to allocate this object, dynamically allocated
        Foo Obj2; //automatic, runs through the life of the object.
    }
    
  • You could, but an alternate solution for assigning addresses would be using void functions that take a parameter, which sets the the object's reference.

    void GetVar(int *Address_Holder)
        {
            //assign address
        }
    
Syntactic Fructose
  • 18,936
  • 23
  • 91
  • 177
0

If you want to control when to allocate memory to an object and when to delete it, then use pointers. If you have object of huge size, then use pointers as passing pointers to functions will be faster than passing the object itself(or u can pass by reference). In any other case, using objects rather than pointers is advisable as use of pointers is highly error-prone.