How to declare struct A that contains instances of class B, where class B has functions that return struct A?

StackOverflow https://stackoverflow.com/questions/7864418

  •  11-02-2021
  •  | 
  •  

Question

I tried my best to describe the goal in the title, but here it is in code:

struct Bar {
    Foo one;
    Foo two;
}

class Foo {
    Bar function();
}

I know this won't work, but how would I accomplish the idea? The reason I'm wanting to make the struct global is because it's used in main.cpp as well. I've already tried declaring the struct inside the class, then defining the struct outside the class as Foo::Bar { } but that doesn't work either.

The reason I'm wanting to do this is because I have functions that need to return more than one variable, such as a divide function that returns both the quotient and remainder. The problem is, however, that multiple instances of a custom class (BigInteger) are being returned.

Was it helpful?

Solution

Since Bar contains instances of Foo, the latter cannot be incomplete in the declaration of the former. So you'll need to declare Foo before declaring Bar. However, since Foo contains a function that returns a Bar object you'll have to forward declare Bar before declaring Foo.

struct Bar;

class Foo {
    Bar function();
};

struct Bar {
    Foo one;
    Foo two;
};

Bar Foo::function()
{ 
  return Bar();
}

Note that the actual definition of Foo::function can only appear after the declaration of Bar since the function needs to instantiate a Bar object.

OTHER TIPS

You just need to do class forwarding like this:

class Foo;


struct Bar {
    Foo *one;
    Foo *two;
};

class Foo {
    struct Bar function();
};

This declares the class without actually defining it, thus making it usable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top