Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 277
Shreyas Avatar asked Aug 19 '13 09:08

Shreyas


People also ask

Can a constructor be a friend function?

sure it does. It should work, so there must be a specific syntactic problem in the OP's code, or maybe a misunderstanding regarding how friendliness works.

Can constructors call other member functions?

In general, special member functions shouldn't be called explicitly. Constructor and destructor can also be called from the member function of the class. Example: CPP.

Is constructor a member function?

A constructor is a special member function that is called whenever a new instance of a class is created.

Can we declare constructor as inline?

Constructors may be declared as inline , explicit , friend , or constexpr . A constructor can initialize an object that has been declared as const , volatile or const volatile .


1 Answers

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)

like image 76
Luchian Grigore Avatar answered Oct 19 '22 13:10

Luchian Grigore