Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

forward declare a type previously declared as a class as a struct

Tags:

c++

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
{

};
like image 612
Guillaume Paris Avatar asked Oct 20 '16 07:10

Guillaume Paris


People also ask

Can you forward declare a struct?

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).

What is forward declaration of class in c++?

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 };

Why use forward declaration c++?

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.


1 Answers

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 classwould 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.

like image 111
eerorika Avatar answered Oct 06 '22 23:10

eerorika