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.
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.
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.
A constructor is a special member function that is called whenever a new instance of a class is created.
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 .
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With