-1

Suppose there are 3 functions f1,f2,f3

They are used in a circular way. f1 requires f2 f2 requires f3 f3 requires f1

So, when writing code we have to use function prototype to avoid errors.

But what about structures? How can we do this with structures, as struct prototypes are not allowed in C++

Aryan Agarwal
  • 23
  • 2
  • 5
  • 1
    I think you might be looking for forward declaration. Which is the actual name of what you're calling a prototype. You can't actually have f1 contain a f2 which contains a f3 which contains a f1 because that f1 would contain an f2 which would contain an f3 which would contain a f1 would contain an f2 which would contain an f3 which would contain a f1 would contain an f2 which would contain an f3 which would contain a f1 would contain an f2 which would contain an f3 which would contain a f1 would contain an f2 which would contain an f3 which would contain a f1... See the problem? – user4581301 Dec 01 '20 at 05:51
  • okay i got your point! – Aryan Agarwal Dec 01 '20 at 05:53

2 Answers2

0

At least one of the structs can only refer to the other by pointer or reference and must declare the struct like the following (pointless code, simply demonstration):

struct struct1;
struct struct2
{
  struct1 * ptr;
  size_t count;
};

struct struct1
{
  void foo(struct2 s2) { /* */ }
};

It would also be possible to do this with an elaborated declarator but that is unusual:

struct struct3
{
  struct struct4 * ptr;
  size_t count;
};

struct struct4
{
  void foo(struct3 st3) { /* */ }
};
SoronelHaetir
  • 14,104
  • 1
  • 12
  • 23
0

What you call "struct prototype" is known as forward declaration. For example:

struct A; //forward declaration of A

struct B 
{ 
   A* a;
}; //definition of B

struct A 
{
   B b; /*need definition of B prior to this point*/
}; //definition of A

After forward declaration, you can use only use a pointer or reference to the struct. You need definition of a struct to use it as a member.

Eugene
  • 6,194
  • 1
  • 20
  • 31