Reputation: 467
Is there any way to not allow private construction in friend function, In case we do have private constructor with friend function in our class. Only Static method should be responsible for object creation and other than this compiler should flash error message
#include <iostream>
#include <memory>
using namespace std;
class a
{
public:
void see ()
{
cout<<"Motimaa";
}
static a& getinstance()
{
static a instance;
return instance;
}
private:
a() {};
friend void access();
};
void access ()
{
a obj;
obj.see();//still friend function can access
}
int main()
{
a::getinstance().see();
access();
return 1;
}
Upvotes: 2
Views: 698
Reputation: 2114
Friend functions can access all private members and variables, but there is a potential workaround for your problem, assuming you are trying to explicitly stop accidental use of the default constructor.
You could potentially make the default constructor kill the program. Now, create a second constructor that takes at least one argument, even if it's a meaningless argument.
Here's an example:
private:
a() { cerr<<"Invalid call to constructor for object a!"; exit(); };
a(bool dummyArg) {}
public:
static a& getInstance() {
static a instance(true);
return a;
}
Upvotes: 1
Reputation: 311058
friend functions have access to all members of the befriended class.
Upvotes: 0