are copy and move constructors automatic friends?
Asked Answered
G

2

14

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;
}
Garibull answered 25/11, 2019 at 6:56 Comment(3)
This is the very same class. So ne friend is needed.Monohydroxy
See #6921685 - in short, access control in C++ does not discern between object instances, only between different types.Davao
When you write "another my_str class" it's a straight-up mistake. It's another my_str instance, and other comments and answers explain what that entailsHugohugon
I
21

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.

Indubitability answered 25/11, 2019 at 7:15 Comment(0)
I
10

Member functions of the class itself always have access to the private members, no matter whether the member function is defined in-class or out-of-class and no matter whether it is a special member function such as a copy/move constructor.

Therefore they are not friend of the class, because that doesn't make any sense. They are already part of the class. Still, they have access to all private members, not because they are friends, but because they are part of the class.

If it wasn't possible to initialized members in a constructor (because they are inaccessible), then the whole concept of member accessibility would be pointless. (How would you initialize the member?)


Also, accessibility is not in any way a matter of the object on which a member is accessed. Accessibility is a matter only of where in the code a name (the name of the member) is used. If a function can access the member of one instance of a class, then it can also access the member of another instance of the same class.

Inexactitude answered 25/11, 2019 at 7:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.