0

I am having a simple C++ problem but I am not sure how to solve this.

I have two classes, A and B which are not inherited in anyway. A is Client class, and B is a class that stores a list of Client (A class).

I want only B to instantiate and destroy the class B, but I want other parts of my code to be able to call methods within class A.

Initially I had the following:

class B {
public:
    class A {
        public:
            void setX(int val);
            int getX();
        private:
            int x;
            A();
            ~A();
    };

    B()
    ~B()
    ....
};

This allows me to call A's constructor/destructor from B, and makes A's constructor/destructor private from the rest, but calling setX() and getX() on A became troublesome as I have to call B::A.

I thought putting A in it's own file (it's own class, not nested), as other classes can call methods on A. But now B cannot access A's constructor/destructor as it is private. If I make it public, then anyone can create an object of class A.

I am not sure what's the best way to do this. If A is it's own class, how can I keep the constructor/destructor available only to B please, while other classes can call setX() and getX() on an object from A please?

user1777907
  • 1,355
  • 4
  • 12
  • 28

2 Answers2

2

Declaring A in its own, non-nested class but with a friend class of B should do the trick.

Friend classes

Leaving you with:

class B{
public:
    B()
    ~B()
    ....
};

and

class A {
    friend class B;
    public:
        void setX(int val);
        int getX();
    private:
        int x;
        A();
        ~A();
};
Egg
  • 1,986
  • 16
  • 20
0

I think you might messed up.(Or I did when reading your example! :P)

Declaring a nested class makes the nested class able to access all member of the nesting class and not the inverse as I understood from your explanation.
I mean: B within A means that A access al member of B, not the inverse!
Nested Classes Question(Check second response, not first!)

If when saying in your question "I want only B to instantiate and destroy the class B" you mean "I want only B to instantiate and destroy the class A" then you have two options.

You can either make B nested class of A, letting B access al private stuff of A or use friend classes.(Check @Egg response)

Community
  • 1
  • 1
Mario Corchero
  • 5,257
  • 5
  • 33
  • 59