Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disadvantages of forward declaration?

In C++ and Objective-C, I've gotten into the habit of forward-declaring any necessary classes that do not need to be defined in the header, and then importing the header files defining those classes in source files if needed.

Is there ever a situation in which this wouldn't be a good idea?

(I know the big disadvantage of forward declaration is the limited usability of an incomplete type. For the purpose of this question, assume that in the header I only need to use the forward-declared class as an incomplete type.)

like image 297
Luke Avatar asked Nov 02 '11 14:11

Luke


People also ask

Why are forward declarations bad?

A forward declaration is not so much dangerous in itself, but it is a code smell. If you need a forward declaration, it means two classes are tightly coupled, which usually is bad. Thus it is an indication that your code may need refactoring.

What is the advantage of forward declaration?

One big benefit is faster compilation times, as a forward declaration takes less time for the compiler to parse than a complete class definition. This can make a very significant difference for large projects with many include files.

Are forward declarations good?

The Google style guide recommends against using forward declarations, and for good reasons: If someone forward declares something from namespace std, then your code exhibits undefined behavior (but will likely work).

Should I use forward declaration or include?

As the name itself implies, forward declaration is just a Declaration and not a definition. So, you will declare saying the compiler that it is a class and I just declaring it here and will provide you the definition when am gonna use it. So, normally you forward declare in the Header file and #include in the .


1 Answers

Sometimes you can change the semantics of the program subtly without raising any errors

class Foo;

template < typename T>
struct Trait
{
    static const int MY_TYPE = -1;
};

// Lets say this is Foo.h
//class Foo
//{
//};
//template<>
//struct  Trait<Foo>
//{
//  static const int MY_TYPE = 1;
//};

void TestFunction(Foo& f)
{
    std::cout << Trait<Foo>::MY_TYPE << std::endl;
}

Consider the above code and the commented out code lives in a header. If the header is included TestFunction will print 1 otherwise -1

like image 187
parapura rajkumar Avatar answered Oct 12 '22 23:10

parapura rajkumar