简体   繁体   中英

Function declared outside class scope but not friend. How does this work?

I have the following class:

class PhoneCall{
private:
    string number;
public:
    /*some code here */
};

Now, I have declared a function (not friend to PhoneCall ) which does some specific operation and returns a PhoneCall object

PhoneCall callOperation()

Another which takes a PhoneCall object as parameter

void userCall(PhoneCall obj)

I was expecting it not to work unless it is explicity declared as a friend to that class.

Why and how do these functions work even when they are not friend to the PhoneCall class ?

A friend function of a class is defined outside that class' scope but it has the right to access all private and protected members of the class http://www.tutorialspoint.com/cplusplus/cpp_friend_functions.htm

You can pass, manipulate and return instances of a class without beeing its friend, as long as you do not access its private or protected members .

According to N4296. p. 261 :

11.3 Friends

A friend of a class is a function or class that is given permission to use the private and protected member names from the class.

Unless you declare your move or copy constructors as private or protected, the object can be also copied or moved as a whole.

So practically a private PhoneCall constructor will prevent non-friends from instantiating PhoneCall objects:

For example:

class PhoneCall{
    private: PhoneCall(){}
};

This prevents non-friend code from instantiating the class:

PhoneCall callOperation(){
    return PhoneCall();
}

will results in a compile-time error:

error: 'PhoneCall::PhoneCall()' is private

Edit: Added info on private constructors following MM`s suggestion in the comments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM