0

I'm trying to implement a Copy Constructor for Vectors in C++ and I'm a little bit confused of why this piece of code actually works. Objects doesn't see private members but its reference, in this example, does.

template <typename Data>
class Vector{
private:
    uint size;
    Data* Elements = nullptr;

public:
    Vector()=default;

    Vector(uint);

    //Copy Constructor
    Vector(const Vector<Data>&);

    ~Vector();
};


template <typename Data>
Vector<Data>::Vector(const Vector<Data>& ref){
this->size = ref.size;
this->Elements = new Data[this->size];

for(uint i = 0; i < this->size; i++)
    this->Elements[i] = ref.Elements[i];
}

So...why does my reference 'ref' has access to private members such as size and Elements? Thanks for your help

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
dpfaicchia
  • 53
  • 1
  • 7
  • 1
    Perhaps if you attempted to illustrate what you mean by "Objects doesn't see private members", you might answer your own question, or allow us to understand what you mean. – jxh Apr 05 '20 at 08:25
  • Well... Suppose we are in the main function. Why 'ref' can't access the member 'size' in the main but it can in the Copy constructor body? – dpfaicchia Apr 05 '20 at 08:41
  • 1
    The constructor is a member of the class. `main` is not. – n. m. could be an AI Apr 05 '20 at 08:46
  • 1
    The assumption that `private` / `protected` / `public` relate to objects is a misapprehension. They relate to types. If your function is a member function or friend of type `X` it can "see" `X`'s private members, not just the private members of `this`. Similarly for `protected`. – bitmask Apr 05 '20 at 08:47
  • you can read about the meaning of `private` eg here: https://en.cppreference.com/w/cpp/language/access. And maybe think about it a bit more, if `ref` could not access the private member inside a member function, then where would access be allowed? – 463035818_is_not_an_ai Apr 05 '20 at 08:52

0 Answers0