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.

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

  19. March 11th, 2019 | 9:56 pm

    Very shortly this website will be famous among all blog people, due
    to it’s pleasant articles or reviews

  20. June 25th, 2019 | 5:30 pm

    4d5PYS You are my inspiration, I possess few web logs and rarely run out from brand . The soul that is within me no man can degrade. by Frederick Douglas.

  21. July 4th, 2019 | 1:57 am

    Thank you, I have just been searching for information about this subject for ages and yours is the best I ave found out till now. But, what about the conclusion? Are you sure concerning the source?

  22. QV
    July 17th, 2019 | 3:01 am

    Hi there mates, how is all, and what you would like to say
    on the topic of this post, in my view its actually awesome in favor of
    me.

  23. July 20th, 2019 | 1:56 am

    Hello there, You’ve done an incredible job.
    I’ll definitely digg it and personally suggest to my friends.
    I’m sure they’ll be benefited from this site.

  24. July 20th, 2019 | 8:22 am

    Great web site you have here.. It’s difficult to
    find high-quality writing like yours these days. I really appreciate individuals
    like you! Take care!!

  25. July 21st, 2019 | 10:26 pm

    Awesome blog! Do you have any hints for aspiring writers?

    I’m planning to start my own website soon but I’m a little lost on everything.
    Would you suggest starting with a free platform like WordPress or
    go for a paid option? There are so many choices out there that I’m totally overwhelmed ..
    Any recommendations? Thank you!

  26. July 21st, 2019 | 11:23 pm

    hello!,I like your writing so so much! proportion we keep
    in touch extra about your post on AOL? I require a specialist in this house to unravel my problem.

    Maybe that is you! Looking forward to look you.

  27. July 22nd, 2019 | 5:47 am

    Thanks for finally writing about > Blogging Without A Purpose » C++ Tip:
    Forward Declaration < Liked it!

  28. July 22nd, 2019 | 5:52 am

    Hmm is anyone else encountering problems with the images on this blog loading?

    I’m trying to determine if its a problem on my end or
    if it’s the blog. Any feed-back would be greatly appreciated.

  29. July 22nd, 2019 | 6:05 am

    Do you mind if I quote a few of your articles as long as I
    provide credit and sources back to your webpage?
    My blog is in the very same area of interest as yours and my users
    would truly benefit from some of the information you provide
    here. Please let me know if this alright with you.
    Thanks a lot!

  30. July 23rd, 2019 | 3:05 am

    I’m amazed, I must say. Rarely do I encounter a blog that’s both educative and engaging, and let me tell you, you have
    hit the nail on the head. The issue is something that not enough people are speaking intelligently about.
    Now i’m very happy that I found this in my hunt for something regarding this.

  31. July 25th, 2019 | 2:04 am

    Excellent pieces. Keep writing such kind of information on your
    page. Im really impressed by your site.
    Hello there, You have performed a fantastic job.
    I’ll definitely digg it and in my opinion suggest to my friends.

    I am sure they will be benefited from this site.

  32. July 25th, 2019 | 4:15 am

    I delight in, lead to I discovered just what I used to be taking a look
    for. You have ended my 4 day lengthy hunt! God Bless you man. Have a great day.
    Bye

  33. July 25th, 2019 | 1:21 pm

    Thanks designed for sharing such a pleasant opinion, post is
    nice, thats why i have read it completely

  34. July 26th, 2019 | 6:59 am

    Excellent way of explaining, and nice article to get
    information regarding my presentation focus, which i am going to present in institution of higher education.

  35. August 11th, 2019 | 12:26 am

    I am in fact happy to read this blog posts which carries
    lots of useful data, thanks for providing these data.

  36. August 16th, 2019 | 11:09 pm

    I’m impressed, I have to admit. Seldom do I encounter a blog that’s equally educative and amusing, and let me tell you, you
    have hit the nail on the head. The problem is something which too few men and women are
    speaking intelligently about. I am very happy I stumbled across this during my
    search for something concerning this.

  37. August 28th, 2019 | 6:52 am

    Excellent write-up. I absolutely appreciate this site. Keep writing!

  38. August 31st, 2019 | 6:04 am

    Hi to every , since I am really eager of reading this blog’s post to be updated daily.
    It contains pleasant information.

  39. August 31st, 2019 | 4:33 pm

    No matter if some one searches for his necessary thing, so
    he/she needs to be available that in detail, thus that thing is
    maintained over here.

  40. September 12th, 2019 | 7:56 am

    I know this website gives quality depending articles and additional material, is there
    any other site which presents these information in quality?

  41. September 22nd, 2019 | 11:23 am

    I am truly thankful to the holder of this site who has shared
    this great paragraph at at this time.

  42. September 23rd, 2019 | 9:41 pm

    Hmm it appears like your website ate my first comment
    (it was extremely long) so I guess I’ll just sum it up what I submitted and say, I’m thoroughly enjoying
    your blog. I too am an aspiring blog blogger but I’m still new to everything.
    Do you have any helpful hints for novice blog writers? I’d definitely appreciate it.

  43. September 27th, 2019 | 5:11 am

    Hi it’s me, I am also visiting this website daily, this website is truly good and the users are actually sharing
    good thoughts.

  44. October 9th, 2019 | 4:05 pm

    I am truly grateful to the holder of this web site who has shared
    this wonderful post at here.

Leave a reply