Search code examples
c++classvariablesclass-design

C++ class design: member and local variables


Is there any difference between the following two examples and should one be preferred over the oher:

Example 1:

class A
{
    int i;
    B* b;

    do_something();
    do_something_else();
}

A::do_something()
{    
    do_something_else();
}

Example 2:

class A
{
    int i;

    do_something()
    do_something_else(B* b)
}

A::do_something()
{
    B* b;
    do_something_else(b);
}

Now let's say there are several methods using b is it better to have them all take it as an argument or take no arguments and use a member variable? Is there a difference in performance between the two approaches? I can see the benefits of both, but which one would be preferred?


Solution

  • This really comes down to how your object model fits together and whether an aggregation relationship accurately represents what you are hoping to model.

    Think about whether B in your case truly exhibits a has-a relationship with A (i.e. is it true to say that A has-a B?) For example, in most cases, a car has an engine, so an engine could reasonably be owned / contained by a car. If this is the case then you should probably go with example 1.

    If on the other hand there is no direct relationship but A just needs to act on another object without owning it or containing it then you should stick with example 2. For example:

    Dog myDog;
    Stick aStick;
    myDog.fetches(aStick);
    

    clearly a stick is (hopefully) not an integral part of a dog.

    It is tempting to incorporate variables (especially pointers) into the class for expediency and to make code look nicer (i.e. because you don't have to pass so many parameters,) but if the contained object does not have a strong relationship with the container and / or is managed somewhere else, you very frequently get into complex lifecycle management issues which can counter the very benefits you sought to gain from aggregation in the first place.