If i have a class name app and a class name manager. I want to create inside manager class an app class, I’ve seen two options but I didn’t understand the difference.
choice 1:
//.....
class app; //writing this line outside the declaration of the func
class manager{
//..
private:
app *a;
//...
}
or choice 2:
class manager{
//..
private:
app *a;
//..
}
The
class app;outside yourclass manager { ... }is a forward declaration. It tells the compiler, “appis a class. I’m not going to tell you what it looks like, but trust me, it is.”Think of your compiler as only knowing about this particular file (which I am assuming is a
.hfile) when it compiles. You have said that yourmemberclass includes a pointer to an “app“. “What the heck is an app?” the compiler wants to know. Without the forward declaration (or perhaps an#include app.hor something similar), it doesn’t know, and will fail to compile. By saying at the top,class app;, it knows thatappis a class. That’s all it needs to know to allocate the space for a pointer to it in yourmemberclass.