0

I ran into the following problem:

class School
{
 Manager manager;
}

class Manager
{
 School school;
}

It will require infinite memory, and will cause unnecessary infinite loop.

What is the best way to solve it?

ALUFTW
  • 1,914
  • 13
  • 24
  • 5
    "_It will cause infinite loop._" It would require infinite amount of memory as well, which is (in my opinion) a bigger problem than an infinite loop. Consider using `std::unique_ptr` combined with forward declaration of one of the classes. – Algirdas Preidžius Oct 12 '17 at 02:57
  • Is it possible? I can't understand what you want. – AleXelton Oct 12 '17 at 03:01
  • @A.Godnov lets say I have an object called "school" with an object "manager". Also the "manager" has an attribute called "school". If i'll do something like this : School s; then the inner object manager will be initialized and then the inner object school will be initialized, and so on.. what is the right way to solve it? – ALUFTW Oct 12 '17 at 03:12
  • @algirdas I would agree, purely on the basis that a program requiring infinite memory is clearly impossible, whereas a program with an infinite loop will just run til the heat death of the universe, which could still be useful – Nick is tired Oct 12 '17 at 03:18

1 Answers1

1
class School;
class Manager
{
    std::weak_ptr<School> school;
};
class School
{
    std::shared_ptr<Manager> manager;
};

Depending on what you want to do, you might want to use the shared_ptr in Manager and the weak_ptr in School instead but the concept stays the same.

MichaelE1000
  • 289
  • 2
  • 14