Restricting one class not create object

Hi,
i am a beginner in c++ programming.
i have 3 independent classes A,B,C.i do not want B to create A's object but C can create A's object.how to implement this scinario?
B only creates an A object if you tell it to. So if you don't want it to do that, then don't do that.

1
2
3
4
class B
{
 // this is an example of B which doesn't create an A object
};
thanks for your answer...
but my question is that if you try to create A's object in class B.it should not create?
er... what?

I don't understand what you're asking. Can you clarify?

If you don't want class B to create class A, then just don't put an A object in class B. If you put an A in B, B is going to create an A.
Maybe viddi wants this:
1
2
3
4
5
6
7
8
9
10
11
12
13
class A
{
    A(){} // a private constructor
    friend class C; // grant C access to the constructor
};
class B
{
    A a; // error
};
class C
{
    A a; // OK
};
When I saw the title I thought he was talking about the singleton pattern, but I guess he wants something else. In general, restrictions on the instantiation of an object can be imposed by making its constructor(s) and its destructor private, and declaring friendship to a desired set of classes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class A
{
    friend class C;

private:
    A(){}
    ~A(){}
};

class B
{
public:
    //uncommenting results in
    //compilation error

    //void b_func() {A a;}
};

class C
{
public:
    void c_func() {A a;}
};

int main()
{
    //uncommenting results in
    //compilation error

    //A a;

    return 0;
}

Though, I don't see how that would be useful... (but maybe I'm just missing something)
As Disch said, if you don't want B to create an A object, just don't tell it to :P

EDIT: That's what I get for checking my posts two and three times before submitting them... -.-
Last edited on
That would only be useful for inheritance, when using abstract classes. In this context, it's not really useful in any way.
m4ster r0shi wrote:
1
2
3
4
5
6
7
8
class A
{
    friend class C;

private:
    A(){}
    ~A(){}
};


Why is there a private keyword there? Aren't classes private by default?

EDIT: v OK
Last edited on
Yes, they are. I put the keyword there for emphasis.
Topic archived. No new replies allowed.