简体   繁体   中英

Pass parent class to constructor of another class

I have several classes in my application, and I'd like to keep the interaction amongst classes restricted to the base classes. To make this concrete, right now I want to do something like this:

    class A
    {
    data 

    public:
       void method();
    };

    class A_child : public A
    {
    //stuff
    };

    class B 
    {
    public:
        B(class A *a);
    };
   class B_child : public B
   {
   public:
        B_child(class A *a);
        B_method(); // does some stuff with data in A and B.
   };

Although in actuality each of the classes have separate header files, so there's a lot of includes back and forth...

In the cpp file for A_child I want to be able to use B_child (or B, for that matter). But I don't know how to avoid having to call something like

void A_child::method()
{
   // stuff

    B_child *example_B;
    example_B = new B_child(this);
    example_B->B_method();

  // more stuff
}

It doesn't have to be

example_B = new B_child(this);

necessarily, it just has to have some way of passing the parent class of A_child into the constructor of B or B_child.

What I'd like to do is avoid having to define B_child as something like:

   class B_child : public B
   {
   public:
        B_child(class A_child *a_child);
        B_method();
   };

instead of what I have above, because this seems to imply that B_child has to work with A_child rather than with A. Although this is true, there is nothing in the material that B or B_child work with that require A_child - the data in A, not A_child, suffice.

I am guessing there is a way to do this in C++? Could someone give me an example for how something like this works or a link to a page that might explain how to do this?

Thanks.

If the B_child constructor takes an A * , you can pass an A_child * to it, since A_child "is-an" A (via public inheritance). Did you try doing this and encounter an error?

You can add parent field in A class:

class A {
  B_child* parent;
public:
  void setParent(B_child* p) {
    parent = p;
  }
}

next in B_child constructor:

B_child::B_child(A* a) {
  // stuff
  a->setParent(this);
}

then you access the parent object inside A_child method:

void A_child::method() {
  if(parent)
    parent->B_method();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM