C++ Tip: Forward Declaration

Yesterday I managed to solve something that was bugging me for some time now in my project. I thought it couldn’t be done in C++.

While I was looking at the KDE source code, I found out about forward declaration of classes. This solved my problem of a circular dependency I was having between two of my classes. I have the following class hierarchy:

Component
      |
      +—Container
            |
            +—Window

Now, Window inherits from Container which inherits from Component. Let’s focus on the Component and Container class. Both Component and Container are abstract classes meaning that you can’t create an object of these classes. A Container is basically a Component that can hold other Components. Now Components will have Container’s as parent. So I need an instance variable of type Container inside of Component to point to the parent of a Component. But the problem was that Container was inheriting from Component, so how was I suppose to be able to use Container inside of the base class Component. The answer came from using a forward declaration.

Here was my code:

//Component.h
class Component
{
    protected:
        Container *parent;
        …

    public:
        void setParent(Container &c);
        …
};

//Container.h
class Container : public Component
{
    protected:
        …

    public:
        …
};

Of course the compiler complained because it didn’t recognize Container as a type, so I changed my Component.h file and added a forward declaration:

//Component.h
class Container;

class Component
{
    protected:
        Container *parent;
        …

    public:
        void setParent(Container &c);
        …
};

This worked. But I had another problem. I actually needed to use functions from the Container class inside of my class implementation. My class implementation looked something like this:

//Component.cpp
#include “Component.h”

void Component::setParent(Container &c)
{
c.add(*this); //Some function from the Container class.
}

But the compiler complained because Container wasn’t defined. It was declared, but not defined (those are very different). So to fix this, I included the Container header in the Component implementation file:

//Component.cpp
#include “Component.h”
#include “Container.h”

void Component::setParent(Container &c)
{
c.add(*this); //Some function from the Container class.
}

The compiler didn’t complain. It compiled, no warnings. The code worked. So that’s how you can resolved dependency between classes even if one of the class is a base class and the other is the derived class.

18 Responses to “C++ Tip: Forward Declaration”

  1. RinaNJ
    June 13th, 2006 | 4:58 pm

    Great explanation; this is usually the point where
    eyes glaze over when someone is learning C++; it certainly was for me.

    BTW, love your posts about Haiti. Brings back good memories.

  2. May 20th, 2007 | 11:56 pm

    Like many people, inside foo.cpp I make a habit of including only foo.h.

    However, your solution is so simple, and what it does is so clear, we now have the “Marv rule” in our style guidelines.

    Complete obviousness is what makes a great tip great. Thanks a lot.

  3. Venkatesh
    May 31st, 2007 | 8:19 am

    Nice explanation, but some compilers give you an compile time ‘class’ type redefinition error if you include “Container.h” and if container.h contains Component.h (recursive inclusion). So the solution is to add #pragma once at the beginning of the header files.

  4. September 11th, 2013 | 8:59 pm

    セリーヌ 財布

  5. December 17th, 2015 | 3:15 pm

    Articles like these put the consumer in the driver seat-very imtantorp.

  6. April 6th, 2016 | 8:01 am

    That’s a smart answer to a difficult question.

  7. April 28th, 2016 | 8:05 pm

    Und warum hat der nächste Schuss nicht gesessen? Bond ballert in der Zeit sonst 10 Statisten ab.Und dann eine leere Ubahn, genau getimt.Am schlimmsten fand ich, gerade als Date Doktor aber die Balz-Dialoge mit ihm und den Mädels. Die waren nicht peppig und erfrischend, sondern so möchte-gern-cool und dadurch öde und unglaubwürdig.

  8. April 28th, 2016 | 8:20 pm

    Arab Muslim, Ates and Myotis gave a good answers. If you have a wife….the prophet did asked one of his companions to shave his private part before he enter his village to meet his wife (after fight a war). Shaving your private part and under your armpits destroys the habitat of harmful bacteria. Keep clean always.

  9. April 30th, 2016 | 8:33 pm

    Hiya, I’m really glad I’ve found this info. Nowadays bloggers publish only about gossips and web and this is really irritating. A good web site with exciting content, that is what I need. Thank you for keeping this website, I will be visiting it. Do you do newsletters? Cant find it.

  10. June 5th, 2016 | 12:18 am

    Gløymde å seie at eg har vore på kurs tirsdag og torsdag og skal jobbe i ein annan samanhang etter jobb til seine kvelden i dag, så eg blir ikkje å finne her det neste døgeret heller.

  11. July 20th, 2016 | 9:16 am

    I have to admit I love high heat fast food, when I first started cooking for myself a lot of my recipes were stir fries. In fact we usually still have them at least once a week. I love them because of the immediacy and the flavours. However once you realise that as long as you put the slow cooker on before you go out for the day, you can have dinner on the table even faster than the fastest of stirfry!

  12. July 20th, 2016 | 10:34 am

    I’d still plowww Jwowww.”Get in line.I don’t mean behind me. I mean behind the 8 guys currently running a train on her somewhere./would also plowwwww her like my life was ending in a week.

  13. July 23rd, 2016 | 6:12 am

    Every time I have a dream, I dream about certain people. I don’t miss them or have feelings for them but in my dreams I do and it feels so real. How come?

  14. August 9th, 2016 | 6:14 am

    wow… I are not able to think you threw all these bananas out… all those you have proven within the photo earlier mentioned glance fine to me. The bruised or additional ripe types would have created exceptional smoothies & banana bread what a waste!

  15. September 30th, 2016 | 2:25 pm

    Very well written story. It will be useful to everyone who usess it, including myself. Keep up the good work – i will definitely read more posts.

  16. October 22nd, 2016 | 10:28 am

    Interesting. I came across this blog from the design awards. But it looks like you’re doing a very similar route that I did last year! , are you stopping in HCM?

  17. April 4th, 2017 | 3:55 pm

    Wer seinen neuen Schlafraum einrichten möchte, jener wird meistens seinen Traum auf ein großes Ruhelager verwerfen, da sich einfach der Platz für dieses Wunschbett nicht ausfindig machen lässt. Oftmals wird das Platzieren eines Schranks oder einer Kommode als relevanter angesehen, dadurch hinlänglich Stauraum zugegen ist. Doch welche Person sich in der riesigen Bettenwelt umsieht, der wird erkennen, dass er sich ein Bett in Wunschgröße erstehen kann und so die gewünschte Liegefläche und hinlänglich Platz und auch Lampen verwenden kann. Vor allem in modernen Kinderzimmern ist der Platzmangel ausgebrochen und so ist das Funktionsbett ein gerne gesehenes Kinderbett, dass mittels seine kernigen Materialien wie Holz voll dem Trend zu einem heilenden Wohnraum folgt.

  18. September 3rd, 2017 | 3:53 am

    It’s good to see this information in your post, i was looking the same but there was not any proper resource, thanx now i have the link which i was looking for my research.

Leave a reply