mikip
mikip

Reputation: 23

C++ Accessing a private structure from another class

I have a class as shown below:

class B;
class A
{
   public:
       A();
      ~A();
      void createStuff(.......); //??

  private:
      B *b;
};

The object B contains another of class 'C' which has about 20 class member variables.

I want the user of class A to be able to call the function createStuff(...) with a set of arguments so that I can construct the object C. What is the best way of doing this?

Upvotes: 1

Views: 1053

Answers (4)

Eugene K
Eugene K

Reputation: 388

In any case you should look at B class, how it implement initialization of C object, can it be controlled (If can't - you should extend interface of class B and add this functionality)?

If C definition is accesible for A maybe you can use constructor of B in such way:

void A::createStuff( const C& c)
{
    b = new B(c); 
}

Upvotes: 0

Jonathan Leffler
Jonathan Leffler

Reputation: 753525

The variable of type C belongs to class B; it mediates the access to the data in C. Class B has constructors; you will use those to set the variable of class B in order, and it is B's job to ensure that the C is correctly managed.

If you need more control over C, then you have a design problem. Either your class A needs its own variable of class C to control, or class B does not provide the tools you need and needs fixing, or you are misguided in thinking you need access to, and therefore direct control over, the contents of the variable of class C.

The Law of Demeter is a guide in such scenarios; you seem to be wanting to contravene it.

Upvotes: 1

Pete
Pete

Reputation: 10871

With what you have posted it looks like something like this may work:

class B
class A:
{
   public:
       A();
      ~A();
      void ceateStuff(.......); //??

  private:
      B *b
}
void A::createStuff(argument1, argument2...)
{
    C = new C(argument1, argument2...) //You now have an instance of C with the arguments pass in to createStuff();

}

Upvotes: 1

David Heffernan
David Heffernan

Reputation: 612804

The mechanism for classes to grant access to their private members is called friendship.

Upvotes: 2

Related Questions