friend default constructor

M

mc

Hello,

I'm trying to create a class (A) with a default constructor friend to
another one (B) as follows:

class A
{
public:
A(int a);
~A();

private:
A(); // default constructor
}

class B
{
// must be able to use A::A()
}

What I need is that only A and B can use the private default constructor
(A::A()). By adding a "friend class B;" in class A, I got it to work but I
do not want B to be able to access the whole of A. Is there a way to do
this? Thank you in advance.

Regards,

MC
 
M

mc

Thank you.

Victor Bazarov said:
You need a proxy friend (or a friend proxy). There is no direct way, I
believe, you would have to rely on copy-construction (and RVO).

class A
{
public:
class defaultAmaker
{
// everything is private
static A makeA() { return A(); }
friend class B;
};

friend class defaultAmaker;
...
};

class B
{
A a = A::defaultAmaker::makeA(); // constructs A using A::A()
}

V
 
H

huili80

Hello,

I'm trying to create a class (A) with a default constructor friend to
another one (B) as follows:

class A
{
public:
    A(int a);
    ~A();

private:
    A();   // default constructor

}

class B
{
  // must be able to use A::A()

}

What I need is that only A and B can use the private default constructor
(A::A()).  By adding a "friend class B;" in class A, I got it to work but I
do not want B to be able to access the whole of A.  Is there a way to do
this?  Thank you in advance.

Regards,

MC

you could also try this:


class B; // forward declare B but define it later

class A
{
public:
A(int a);
~A();

private:
A(); // default constructor

friend class B; // say B is a friend

}

class B // now define B
{
// must be able to use A::A()

}
 
M

mc

Victor's correct: B can see everything in A and the forward declaration is
not needed (at least with GCC)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top