Below there are 2 examples of using forward declarations in header files:
1.
class SomeClass;
class MainClass
{
SomeClass* NewInstance = nullptr;
}
2.
class MainClass
{
class SomeClass* NewInstance = nullptr;
}
My question is, is there a difference in performance, compilation time or anything at all between these 2 examples? I understand that this is a rather trivial situation but I am more interested in larger environments where forward declarations are constantly used.
Yes. In your first way you can reuse this class declaration multiple times, and in your second way, you can do it only ones (unless you retype 'class' before). More then that, let's have a look on your second way:
class MainClass
{
public:
class SomeClass* NewInstance = nullptr;
};
If you want to pass to class's constructor an instance of this class, you might want do something like that:
class MainClass
{
public:
MainClass(class SomeClass* a) { // The compiler think it is like "struct SomeClass* a"
this->NewInstance = a;
}
class SomeClass* NewInstance = nullptr;
};
What that means that you can't pass this class by parameter to this class. In Your first way, this isn't a problem at all:
class SomeClass;
class MainClass
{
public:
MainClass(SomeClass* a) {
this->NewInstance = a;
}
SomeClass* NewInstance = nullptr;
SomeClass* aNewInstance = nullptr;
};
EDIT: Another difference between them is that some IDEs (like CLion for example) will warn you in the writing level that they are not recognize the function or the variables of the class that you declared in class SomeClass* a
way. For example:
class MainClass
{
public:
class SomeClass* NewInstance = nullptr;
};
class SomeClass {
public:
int a = 5;
int b() {
cout << "aaa" << endl;
}
};
int main() {
MainClass a;
SomeClass b;
a.NewInstance = &b;
a.NewInstance->b(); // class 'SomeClass' doesn't have function 'b'
cout << a.NewInstance->a << endl; // class 'SomeClass' doesn't have field 'a'
return 0;
}
This code works at the compile and run times, but it makes the code fully with false alarms about undeclared function and variables. In the first way of forward declaration, it isn't a problem- again:
class SomeClass;
class MainClass
{
public:
SomeClass* NewInstance = nullptr;
};
class SomeClass {
public:
int a = 5;
int b() {
cout << "aaa" << endl;
}
};
int main() {
MainClass a;
SomeClass b;
a.NewInstance = &b;
a.NewInstance->b();
cout << a.NewInstance->a << endl;
return 0;
}