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
{
};
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
{
};
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.
struct Bar;
class Bar;
These are equivalent, it doesn't matter.
but some use cases exist ?
No special ones IIRC.
From the language's point of view, there is no difference between forward-declaring a class
as struct
or class
.
class Foo;
struct Foo;
class Bar;
struct Bar;
class Foo{}; // 100% ok
struct Bar{}; // 100% ok
Unfortunately, some compilers mangle those keywords differently. As described here, this can be nasty when you're depending on name mangling being the same.
Consider:
// process.h
struct Foo;
void processIfNotNull(Foo*);
// foo.h
class Foo{};
If you export such function in your shared library, your users will not be able to call processIfNotNull
unless they have the definition of Foo
.
It's not usefull.
In C++ the difference between struct and class is that for struct members are public by default.
Considering this, in your example it could just confuse the code reader to determine if your class will behavior as a struct or a class.
You can read this post for further information : When should you use a class vs a struct in C++?