Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

are copy and move constructors automatic friends?

We can access private variables of another class when we define copy or move constructors. Does C++ make them friend to each other automatically?

For example:

my_str::my_str(my_str&& m) 
{
    size_ = m.size_; //accessing private variable another my_str class
    buff_ = m.buff_; //accessing private variable another my_str class
    m.buff_ = nullptr;
    m.size_ = 0;
}
like image 710
redkont Avatar asked Nov 25 '19 06:11

redkont


1 Answers

It is not considered friend, but yes, any member function of class my_str can access private members of all instances of type my_str, not just the this instance:

class my_str {
    void foo(my_str& other) {
        // can access private members of both this-> and other.
    }

    static void bar(my_str& other) {
        // can access private members of other.
    }
};

The general idea behind it is to allow 2 or more objects of the same type to interact without having to expose their private members.

like image 179
Shloim Avatar answered Sep 20 '22 21:09

Shloim