Is there any interest to forward a class as a struct and vice versa ? It seems to be perfectly legal, but some use cases exist ?
struct Bar;
class Foo
{
Bar * bar_;
};
class Bar
{
};
In C++, classes and structs can be forward-declared like this: class MyClass; struct MyStruct; In C++, classes can be forward-declared if you only need to use the pointer-to-that-class type (since all object pointers are the same size, and this is what the compiler cares about).
In C++, Forward declarations are usually used for Classes. In this, the class is pre-defined before its use so that it can be called and used by other classes that are defined before this. Example: // Forward Declaration class A class A; // Definition of class A class A{ // Body };
A forward declaration allows us to tell the compiler about the existence of an identifier before actually defining the identifier. In the case of functions, this allows us to tell the compiler about the existence of a function before we define the function's body.
There isn't a use case any more or less than there is a use case for forward declaring with the same keyword. It makes no difference to the meaning of the program. The class-key identifier only makes a difference when defining the class.
The above applies to standard compliant compilers. Some non compliant ones might handle the declarations differently in which case there is a case for using the same keyword in particular.
Ok, here is a practical use case. Let's say you've implemented a class with the struct
keyword. Over time, the class is widely used across multiple code bases and it is declared in many headers using the same keyword. At a later time, perhaps after adding a ton of features, you decide that class
would be more appropriate and you refactor the code. Now, there isn't a point in refactoring all the unrelated depending code bases to use the new keyword.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With