Class prototyping

I put several instances of class b in class a, but this causes an error because class a does not know what class b is.

Now I know that I can solve this problem by writing a bac file, but it interferes with reachability and also annoys me. I know that I can prototype my functions, so I do not have this problem, but I can not find material on how to prototype a class.

Does anyone have an example of prototyping a class in C ++.

since there seems to be some confusion, let me show you what I want

class A { public: B foo[5]; }; class B { public: int foo; char bar; } 

but this does not work, because A cannot see B, so I need to put something in front of me, if it was a function, I would put A (); then implement it later. how can i do this with a class.

+6
source share
4 answers

You can declare all your classes and then define them in any order, for example:

 // Declare my classes class A; class B; class C; // Define my classes (any order will do) class A { ... }; class B { ... }; class C { ... }; 
+17
source

You are looking for ads.

 class A; class B { A MakeA(); void ProcessA(A a); }; class A { B bs[1000]; }; 

If you redirect a class declaration, you can

 declare functions taking and returning it or complex types made of it declare member variables of pointer or reference to it 

This basically means that in any case that does not end with instances of A inside B and vice versa, you should be able to declare and define any interface between A and B.

+4
source

The usual way to resolve circular dependencies is to use a direct declaration:

 // Bar.h class Foo; // declares the class Foo without defining it class Bar { Foo & foo; // can only be used for reference or pointer }; // Foo.h #include <Bar.h> class Foo { Bar bar; // has full declaration, can create instance } 

You can provide the full declaration and definition in another file. Using the forward declaration, you can create pointers and class references, but you cannot create instances, since this requires a full declaration.

+2
source

class b;

  class a {
 public:
      b * inst1;
 };
 class b {
 ....
 };

This is what you need?

+1
source

Source: https://habr.com/ru/post/889448/


All Articles