I just had an “oh, that’s how you fix those” moments while playing with some C++ code. I’ve played with C++ a lot in the past (and read some books), but never really dug much deeper than tutorials and trying some simple algorithms. That’s probably why I’ve never come across the following example (though in fact I probably read about it somewhere before).
Say you’ve got a class called Car, and Car has a class called Engine. Now imagine for a moment that Engine has a reference to an instance of a Car, and Engine has a reference back to it’s parent Car instance.
// car.h #include "engine.h" class Car { private: Engine *_engine; public: // ... }; //engine.h #include "car.h" class Engine { private: Car *_car; public: // ... }
In most programming languages, this just isn’t going to be an issue. But it turns out it’s actually a common problem in compiled languages. We’re talking about C++, and yes, this is an issue despite having proper inclusion guards. This type of code may generate error codes such as C2143 & C4430. But, as it turns out this issue is quite trivial to fix if you know what to do when you recognize this scenario. The fix is called a forward declaration, and it pretty much breaks up the cyclic dependency so the compiler can carry on.
//engine.h #include "car.h" class Car; // <- Forward declaration class Engine { // ... }
Easy. I hope this helps any noobs stumbling into the same issue.
i knew about this 20,000 years ago and i don’t even know c++ wow you are a newb i don’t believe it!!!