Shreyas
Shreyas

Reputation: 351

Can a constructor function be a friend in c++?

Can we declare constructor of a class to be friend? I think it cannot be. But i read somewhere that it can be, but i was unable to do. If yes can you please provide some example code.

Upvotes: 25

Views: 9370

Answers (1)

Luchian Grigore
Luchian Grigore

Reputation: 258618

Yes it can:

class Y
{
public:
     Y();
};
class X
{
private:
     void foo() {}  
     friend Y::Y();
};
Y::Y() 
{
   X x; x.foo(); 
}  

As per 11.3 Friends [class.friend]

5) When a friend declaration refers to an overloaded name or operator, only the function specified by the parameter types becomes a friend. A member function of a class X can be a friend of a class Y.

[ Example:

class Y {
friend char* X::foo(int);
friend X::X(char); // constructors can be friends
friend X::~X(); // destructors can be friends
};

—end example ]

(emphasis mine)

Upvotes: 29

Related Questions