简体   繁体   中英

C++ class object inside another class problem

I working on a project and I have a lot of classes that have instances of other classes as fields. The problem is that I must declare the classes in a specific order in order for the code to compile. Example below:

class A{
  public:
    B* b; //unknown type name B
    A(){
      b = new B();
    }
};

class B{
  public:
    B(){
    }

};

The code above does not work, because it says that B is unknown. But, if I declare class B before A it's working fine.

class B{
  public:
    B(){
    }

};

class A{
  public:
    B* b; //Works perfectly
    A(){
      b = new B();
    }
};

In my project, there's no way to re-arrange the classes in order for the error to go away. Is there a way to bypass this error?

In my project, there's no way to re-arrange the classes in order for the error to go away. Is there a way to bypass this error?

You are describing a circular dependency. X depends on Y and Y depends on X . Such dependency is unsolvable. If you can remove a dependency on one class from another class, then it may be possible to re-order the definitions so that all dependencies are satisfied. Sometimes dependency can be removed by introducing indirection.

Note that just because one class definition ( A ) depends on declaration of another class ( B ), that doesn't necessarily mean that it depends on the definition of that class. You can have one class depend on the definition of another class, while still having the dependee class depend on the declaration of the depender.

Furthermore, just because definition of a member function ( A::A ) depends on definition of another class ( B ), that doesn't necessarily mean that the class ( A ) has that same dependency. This is because it is not necessary to define member functions within the class definition.

For example, your example class A does not depend on the definition of B . As such, A can be defined before B :

// declaration of B
// not a definition
class B;

// definition of A
class A{
  public:
    B* b;   // depends on declaration of B
            // does not depend on the definition
    A();
};

// definition of B
class B{
  public:
    B(){
    }
};

// definition of A::A
// does depend on definition of B
A::A() {
    b = new B();
}

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