hannibal
hannibal

Reputation: 21

Creating an object as a private member variable vs. in a member function

What is the difference between creating an object as a private member variable in the class declaration and creating an object in the definition of a method of the class? I know the obvious difference is that one is a global variable and other one makes it local. Under what circumstances should I do the former and later?

Aclass.h

class Aclass{ 
private: 
    AnotherClass someobj1; //option 1
public:  
    void someMethod(); 
};

Aclass.cpp

void Aclass::someMethod(){ 
    AnotherClass someobj2; //option 2 
}

Upvotes: 2

Views: 6114

Answers (5)

Rushikesh Deshpande
Rushikesh Deshpande

Reputation: 93

The absolute rule of programming is define , declare or initialize something when absolutely necessary.It means it will obviously reduce the costs on memory and performance.
That said, when you declare a member variable in a class, memory space will be allocated to it whenever a new object is created. So until and unless you need it in every object, do not declare it in class scope.
Again declaring a variable private is necessary when you don't want any function or class to have access to this variable. Otherwise you should declare it public.
If you define the variable in function scope, then it will take up the memory only when the function is called and will be deleted as soon as the function scope ends.
Overall the definition of class is that it holds data and functions related to that data together. So when you define a class , you should have in mind what data will be present in that class, and then you declare function which will process the data.
The function is basically gets some inputs and processes on that input. At the end returns some data necessary. If you need to declare some variables for the process to be completed then only you declare the variable.

Upvotes: 0

Quentin
Quentin

Reputation: 63154

someobj1 is indeed a member variable. This means that every instance of AClass contains an instance of AnotherClass named someobj1, which has the same lifetime as the instance it is part of.

someobj2 is a local variable of the someMethod function. It will be destroyed at the end of said function.

None of them is a global. Maybe you're mixing them up with static member variables, which have static lifetime (constructed before main begins, destroyed after it ends), just like globals (but they're not exactly global because they're enclosed in the class' scope.

Here's a silly example to make it perfectly clear :

CatBasket gCatBasket; // All cats in the house share the same basket (global)

class Cat {
    Tail _tail; // The tail is part of the cat (member)
    Human *_owner; // The cat remembers his owner for his whole life (member)

    void meow() {
        MeowSound sound; // The "meow" sound only exists while the cat is meowing. (local)
        sound.setAmplitude(17.0f);
        sound.setPurr(true);

        sound.play();
    }

    static bool _beACat;
};

bool Cat::_beACat = true; // Everybody wants to be a cat (static)

Upvotes: 5

TryinHard
TryinHard

Reputation: 4118

We can define the concepts like Association, Composition and Aggregation using the object as a private member.

Consider the following code snippet:

//ASSOCIATION
class Bar
{
    Baz baz;
};
class Foo
{
    Bar* bar;
    void setBar(Bar* _bar)
    {
        bar=_bar;
    }
};

//AGGREGATION
class Bar
{
    Baz baz;
};

class Foo
{
    Bar* bar;
    void setBar(Bar* _bar)
    {
        bar = new Bar;
        bar->baz=_bar->baz;
    }
};


//COMPOSTION
class Bar
{
    Baz baz;
};
class Foo
{
    Bar bar;
}

My understanding is that in:

  1. Association: Foo has a pointer to Bar object as a data member
  2. Aggregation: Foo has a pointer to Bar object and data of Bar is deep copied in that pointer.
  3. Composition: Foo has a Bar object as data member.

However the second type of usage(Object creation in the member function definition) is required whenever the object is to be used for a shorter span of time(rather than the entire lifetime of the object that includes it).

Another difference is with reference to the memory:

The object as a data member will be assigned memory and retained till the object dies. However, the object as a variable in the member function will be allocated memory and deallocated whenever the function is out of scope.

Upvotes: 0

Timo
Timo

Reputation: 2242

The difference that is most important is the lifespan of your AnotherClass instance.

Aclass.h

class Aclass{ 
private: 
    AnotherClass someobj1; //option 1: This instance is accessible from within the Aclass instance as long as the Aclass instance is not destroyed.
public:  
    void someMethod(); //option 1: So someobj1 is available (for reading AND writing in this method. When you call this method twice, you will work with the same instance each time.
    void someMethodToo(); //option 1: someobj1 will also be available in this method for reading AND writing.
};

Aclass.cpp

void Aclass::someMethod(){ 
    AnotherClass someobj2; //option 2: This instance is destroyed when someMethod is done. The method someMethodToo that I described above will never have access to someobj2 either. If you call someMethod twice, each will have it's own someobj2. 
}

Upvotes: 0

Mureinik
Mureinik

Reputation: 312116

A member variable (regardless of its visibility) lives throughout the instance's lifecycle. As long as you have a live instance of AClass, it will retain the value of someobj1. These kind of variables are (traditionally) used to save an object's state which you want to retain from one usage to another.

A local variable defined inside a method is just that - a local variable. It's an auxiliary variable that helps you perform the functionality of the method, and has no meaning (nor is it exist) once the method call is over.

Upvotes: 0

Related Questions