Search code examples
c++classc++11privatecopy-constructor

C++ - Why can a passed object's private variables be accessed directly in the Copy Constructor?


class IntVec
{
public:
     IntVec();
     IntVec(int siz);
     IntVec(const IntVec& temp);

     ~IntVec();

private:
       int* arr;

       int size;
};

IntVec::IntVec()
{
    size = 2;

    arr = new int[size]; 
}

IntVec::IntVec(int siz)
{
    size = siz;

    arr = new int[size];
}

IntVec::IntVec(const IntVec& temp)
{
    size = temp.size; // Why does this not cause an error?  size is a private variable of object temp.

    arr = new int[size];

    for (int i = 0; i < size; i++)
    {
        arr[i] = temp.arr[i]; // Why doesn't this cause an error?  arr is a private variable of object temp.
    }
}

IntVec::~IntVec()
{
    delete[] arr;
}

int main()
{
    IntVec test1(2);

    cout << test1.size; // Causes error (expected), since size is private.
}

I'm unclear why I can access temp's size and arr variables in the copy constructor, since they are private variables. It makes sense why I get an error in main(), but I'm not sure why I don't get an error in the Copy Constructor.


Solution

  • That's because access specifiers are effective per-class, not per-object. So a class method can access private members of any instance of the class.

    All members of a class (bodies of member functions, initializers of member objects, and the entire nested class definitions) have access to all the names to which a class can access. A local class within a member function has access to all the names the member function itself can access.