Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private member variables scope - C++

Tags:

c++

scope

I am just starting with C++ and got some problems in understanding how the scope for private member variables in a class works. Please see the below code

class Foo{
    private:
        std::vector<int> container;
    public:
        // other methods
};

int main(int argc, char* argv[])
{
    Foo* foo = new Foo;
    // other method calls to which foo is passed
    delete foo;
    return 0;
}

In the above code, variable "container" is a private member variable. I am invoking "Foo" instance and passing it to several other methods and classes. Following are my doubts

  1. What will be the scope of variable "container"? Will that variable exist until I delete the instance foo?
  2. Do I need to make the "container" as a pointer to vector?

Thanks for the help

like image 265
Navaneeth K N Avatar asked Nov 25 '25 10:11

Navaneeth K N


1 Answers

  1. Yes, the lifetime of the container member will last as long as the object that contains it exists, which is until you call delete on the pointer pointing to it (foo in your case).
  2. No, there is no reason to do that. Making it a pointer requires you to create a dynamic object of vector<int> which you would need to manage the lifetime of (including calling delete on the container pointer). That's unnecessary here. Assuming you want the container last as long as the Foo object, you are fine with having it directly contained, without doing it with a pointer.

Passing the foo pointer will just pass the pointer. The object that it points to will not be copied, only the pointer pointing to it if necassary. If you know Java, then it helps you if i tell you passing the pointer is the same as just passing a reference to an object in Java, say:

Foo f = new Foo();
// just passes the reference (pointer in C++) to doIt. 
// the actual object is not copied
doIt(f);
like image 117
Johannes Schaub - litb Avatar answered Nov 27 '25 23:11

Johannes Schaub - litb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!