2
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.

  • 4
    The `size` member is a private member of the *class* `IntVec`, and the copy constructor is also a member of that class. [The access specifiers](http://en.cppreference.com/w/cpp/language/access) are per-class, not per-object. – Some programmer dude Feb 19 '18 at 07:45

4 Answers4

2

This is because public/protected/private refer to the class and not the individual object. Therefore all objects in a class as well as static methods can access eachothers internals.

doron
  • 27,972
  • 12
  • 65
  • 103
2
size = temp.size; // Why does this not cause an error?  size is a private variable of object temp.

You misunderstand the access rules.

Access rules don't apply per object.

They apply to types and functions.

The type of temp is IntVec. Any member of an object of type IntVec can be accessed in any member function of IntVec.

Non-member functions and member functions of other classes won't be able to access the private members of an object of type IntVec.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
1

private members have class scope means can be directly used inside the class, you cannot directly use the private members outside the class, since copy constructor is inside the class you can access the private members

vicky
  • 189
  • 2
  • 9
1

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.

iBug
  • 35,554
  • 7
  • 89
  • 134