Class prototype

how do you make the prototype of a class? I’m pretty sure I’ve seen it before but I’m not sure how it looks, the reason is I have two classes that have each other as members so one has to be defined for the other two work, but it’s that for both so i don’t know what to do. If you have a better solution that what I’m thinking with the prototyping do tell. Thanks! :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  #include <iostream> 
  
  // prototype class syntax for Person
  // prototype class syntax for phoneNumber
  
  int main(){
    // use person
  }
  
  class Person{
    phoneNumber a;
    public:
    
  };
  class phoneNumber{
    Person a;
    public:
    
  };
Last edited on
To declare and not define a class, just say class class_name.
 
class person; // no member specification (class body) 
Because the size and member layout of person isn't known, person is an incomplete type until it's defined later:
1
2
// incomplete class type person is completed by this class definition
class person { int foo; };
Before person is complete, it isn't useful for very much. In particular, objects of type person cannot be created until the type is completed.

I have two classes that have each other as members
This program is nonsense and won't compile, for the reasons discussed above:
1
2
3
struct A;  // declares the incomplete class type A
struct B { A a; }; // error: class A has incomplete type
struct A { B b; }; // A is complete here  

Also consider that if A contains B and B contains A, what is sizeof (A)?

What you can do is store a pointer somewhere to break the cycle. The size and layout of person isn't necessary to merely to create a pointer to it.
1
2
3
4
struct A; 
struct B { std::unique_ptr<A> pa; ~B(); };
struct A { B b; };
B::~B() = default;

This is challenging to do correctly. Consider another way to represent the relationships between objects - for instance, with some kind of adjacency list.

What's the bigger picture?
Last edited on
What’s a adjacency list?
How is that challenging to do correctly?
Well I have a Weapon class and a Characters class and my Character has 3 Weapons but Weapon uses information of Character in its () function.
Last edited on
Topic archived. No new replies allowed.