class foo; in header file - c++

Is some one able to explain why header files have something like this?
class foo; // This here?
class bar
{
bar();
};
Do you need an include statement when using this?
Thanks.

The first class foo; is called a forward declaration of the class foo. It simply lets the compiler know that it exists and that it names a class. This makes foo what is called an "incomplete type" (unless the full declaration of foo has already been seen). With an incomplete type, you can declare pointers of that type, but you cannot allocate instances of that type or do anything that requires knowing its size or members.
Such forward declarations are frequently used when two types each may have pointers to each other, in which case both need to be able to express the notion of a pointer to the other type, and so you would have a circular dependency without such a thing. This is needed mostly because C++ uses a single pass mechanism for resolving types; in Java, you can have circular dependencies without forward declarations, because Java uses multiple passes. You may also see forward declarations where the author is under the misguided impression that using forward declarations instead of including the required header reduces compile time; that, of course, is not the case, because you need to include the full declaration (i.e. the header), anyway, and if preprocessor guards are used, then there is basically no difference in compile time.
To answer your question on whether you need the include or not... assuming you only need a partial type, then your header does not need to directly include the header for the type that has been forward declared; however, whoever makes use of your header, when they use your type will need to include the header for the forward declared type, and so you might as well just include the other header.

That's a forward declaration. You need it for example if class bar has a pointer to a foo object, but you don't want to include the whole definition of the foo object immediately.

this is a forward declaration of the class.
In my experience, this is typically done when you have a circular dependency.. for example
in foo.h
--------
#include "bar.h"
class foo
{
public:
foo(bar *bar);
private:
foo *m_foo;
};
and in bar.h
------------
class foo;
class bar
{
public:
void methodFooWillCall();
protected:
std::list<foo *> myFoos;
}

Just curious, why do we need the term forward declaration at all? Isn't a forward declaration simply a declaration (as opposed to a definition)?
class X; // declaration
class X // definition
{
int member;
void function();
};

That's a forward declaration. Consider the following example:
class foo; // you likely need this for the code beneath to compile
class bar {
void smth( foo& );
};
If you haven't included the definition of class foo in such a way that the compiler sees it before compiling the definition of class bar the code will not compile (the compiler will say it doesn't know what foo means) unless you have the forward declaration.

It's a forwards declaration of the class 'foo'. It allows you to declare pointers and references to the class, but not use it (eg. call members or determine its size), because it's not yet defined! It must later be followed up with a full, normal declaration (class foo { ... };).
It's useful for things like declaring two classes which hold pointers to each other, which otherwise would be impossible to set up.

This is called forward declaration. The body of the class foo would be defined at a later part of the file. Forward declaration is done to get around cyclic dependencies: The definition of class Bar requires class Foo and vice versa.
class Bar
{
Foo * foo;
};
class Foo
{
Bar * bar;
};
As you can see, Bar has a reference to Foo and vice versa. If you try to compile this, the compiler will complaint saying that it doesn't know anything about Foo. The solution is to forward declare the class Foo above the Bar (just like you declare the prototype of a function above the main and define its body later).
class Foo; //Tells the compiler that there is a class Foo coming down the line.
class Bar
{
Foo * foo;
};
class Foo
{
Bar * bar;
};

This is called a forward declaration. It is used to make your code aware that the class foo exists. This in turn can be used by the class bar.
It's commonly used to solve circular includes problems. Take this for example
//a.h
#include "b.h"
class A
{
void useB(B obj);
}
and
// b.h
#include "a.h"
class B
{
void useA(A obj);
}
This causes a circular include problem, because a.h includes b.h which in turns includes a.h, to infinity. You can solve this problem by making a forward declaration of each class in each header, like so :
//a.h
class B;
class A
{
void useB(B obj);
}
// b.h
class A;
class B
{
void useA(A obj);
}
Note : Very often when you have a circular include problem, this is indicative of a conception/modelling problem. You should probably ask yourself if your classes are well defined before trying to solve your problem with forward declarations.

Try to think of writing this:
file bar.h:
#include "bar.h"
class Foo
{
Bar* bar_ptr;
}
file foo.h:
#include "foo.h"
class Bar
{
Foo* foo_ptr;
}
This won't work, first due to infinite #include chain, then if you get rid of one of the includes, either Foo won't know what Bar is, or Bar won't know what Foo is.
Try this instead:
class Bar;
class Foo
{
Bar* bar_ptr;
};
file foo.h:
class Foo;
class Bar
{
Foo* foo_ptr;
};

Related

Forward declare a typedef protection

I am attempting to forward declare some variables used only privately in a class to limit the number of headers that I have to include when using this one.
Sadly, the class that I want to forward declare has turned out to be a typedef, and it's a 3rd party library that I can't edit (let's call it "boost::asio::strand" for the sake of argument)
This question Forward declaration of a typedef in C++ Demonstrates that the only solutions are either:
Just include the header and accept it's not possible
Forward declare what would be typedef'ed and add my own typedef
Looking at the second solution, is there any way that I can protect myself from the typedef changing in the library so that the compiler complains about the typedef rather than the usage of an undefined type when the class is removed/renamed and make it less of a maintenance headache?
I would try not to rely on the forward declaration of the original class at all if possible. I may have missed a case but I think a forward declaration is only useful for a purely private use if the type appears in a method signature somehow, or if your class contains a member that somehow points to or references the type, possibly indirectly.
I propose to to forward declare a wrapper for the class and only define that in the implementation file, when the actual class or typedef is known.
Say your class header currently looks like this:
// need header because it contains UglyTypeDef:
#include <UglyHeader.h>
class MyClass {
public:
int theMethod(int a);
private:
void uglyMethod(UglyTypeDef &utd);
int someMember;
UglyTypeDef *utdp;
std::vector<UglyTypeDef *> utds;
};
In this example we could do with a forward declaration, but we do not want to rely on the internals of UglyHeader.
I would change MyClass like this:
class MyClass {
public:
int theMethod(int a);
private:
// move the private method into the implementation file
// hide the ugly typedef
// we safely forward declare our own private wrapper
struct UglyTypeDefWrapper;
int someMember;
UglyTypeDefWrapper *utdp;
std::vector<UglyTypeDefWrapper *> utds;
};
Now in order to make this work, the implementation in the cpp file must change as well:
#include "MyClass.hpp"
#include <UglyHeader.h>
struct MyClass::UglyTypeDefWrapper {
// if possible save another level of indirection
// and store by value, otherwise use a second indirection
// by cleverly wrapping at the right level of abstraction
// this abstraction can be free in many cases
UglyTypeDef td;
};
namespace {
// we completely hide the private method in this file as
// an implementation detail and pass it whatever it needs
// this also helps the compiler to inline it,
// because it knows it cannot be referenced in
// a different compilation unit
// we need to pass all members as needed
void uglyFormerMethod(int &someMember, UglyTypeDef &utd) {
someMember += utd.whatever();
}
}
int MyClass::theMethod(int a) {
utd->td.doWhatever();
uglyFormerMethod(someMember, *utd);
for(auto utdwp: utds) {
utdwp->td.doIt();
}
}

Why does the Qt tutorial build the header class like this? [duplicate]

Is some one able to explain why header files have something like this?
class foo; // This here?
class bar
{
bar();
};
Do you need an include statement when using this?
Thanks.
The first class foo; is called a forward declaration of the class foo. It simply lets the compiler know that it exists and that it names a class. This makes foo what is called an "incomplete type" (unless the full declaration of foo has already been seen). With an incomplete type, you can declare pointers of that type, but you cannot allocate instances of that type or do anything that requires knowing its size or members.
Such forward declarations are frequently used when two types each may have pointers to each other, in which case both need to be able to express the notion of a pointer to the other type, and so you would have a circular dependency without such a thing. This is needed mostly because C++ uses a single pass mechanism for resolving types; in Java, you can have circular dependencies without forward declarations, because Java uses multiple passes. You may also see forward declarations where the author is under the misguided impression that using forward declarations instead of including the required header reduces compile time; that, of course, is not the case, because you need to include the full declaration (i.e. the header), anyway, and if preprocessor guards are used, then there is basically no difference in compile time.
To answer your question on whether you need the include or not... assuming you only need a partial type, then your header does not need to directly include the header for the type that has been forward declared; however, whoever makes use of your header, when they use your type will need to include the header for the forward declared type, and so you might as well just include the other header.
That's a forward declaration. You need it for example if class bar has a pointer to a foo object, but you don't want to include the whole definition of the foo object immediately.
this is a forward declaration of the class.
In my experience, this is typically done when you have a circular dependency.. for example
in foo.h
--------
#include "bar.h"
class foo
{
public:
foo(bar *bar);
private:
foo *m_foo;
};
and in bar.h
------------
class foo;
class bar
{
public:
void methodFooWillCall();
protected:
std::list<foo *> myFoos;
}
Just curious, why do we need the term forward declaration at all? Isn't a forward declaration simply a declaration (as opposed to a definition)?
class X; // declaration
class X // definition
{
int member;
void function();
};
That's a forward declaration. Consider the following example:
class foo; // you likely need this for the code beneath to compile
class bar {
void smth( foo& );
};
If you haven't included the definition of class foo in such a way that the compiler sees it before compiling the definition of class bar the code will not compile (the compiler will say it doesn't know what foo means) unless you have the forward declaration.
It's a forwards declaration of the class 'foo'. It allows you to declare pointers and references to the class, but not use it (eg. call members or determine its size), because it's not yet defined! It must later be followed up with a full, normal declaration (class foo { ... };).
It's useful for things like declaring two classes which hold pointers to each other, which otherwise would be impossible to set up.
This is called forward declaration. The body of the class foo would be defined at a later part of the file. Forward declaration is done to get around cyclic dependencies: The definition of class Bar requires class Foo and vice versa.
class Bar
{
Foo * foo;
};
class Foo
{
Bar * bar;
};
As you can see, Bar has a reference to Foo and vice versa. If you try to compile this, the compiler will complaint saying that it doesn't know anything about Foo. The solution is to forward declare the class Foo above the Bar (just like you declare the prototype of a function above the main and define its body later).
class Foo; //Tells the compiler that there is a class Foo coming down the line.
class Bar
{
Foo * foo;
};
class Foo
{
Bar * bar;
};
This is called a forward declaration. It is used to make your code aware that the class foo exists. This in turn can be used by the class bar.
It's commonly used to solve circular includes problems. Take this for example
//a.h
#include "b.h"
class A
{
void useB(B obj);
}
and
// b.h
#include "a.h"
class B
{
void useA(A obj);
}
This causes a circular include problem, because a.h includes b.h which in turns includes a.h, to infinity. You can solve this problem by making a forward declaration of each class in each header, like so :
//a.h
class B;
class A
{
void useB(B obj);
}
// b.h
class A;
class B
{
void useA(A obj);
}
Note : Very often when you have a circular include problem, this is indicative of a conception/modelling problem. You should probably ask yourself if your classes are well defined before trying to solve your problem with forward declarations.
Try to think of writing this:
file bar.h:
#include "bar.h"
class Foo
{
Bar* bar_ptr;
}
file foo.h:
#include "foo.h"
class Bar
{
Foo* foo_ptr;
}
This won't work, first due to infinite #include chain, then if you get rid of one of the includes, either Foo won't know what Bar is, or Bar won't know what Foo is.
Try this instead:
class Bar;
class Foo
{
Bar* bar_ptr;
};
file foo.h:
class Foo;
class Bar
{
Foo* foo_ptr;
};

C++: Forward declaration of a class with a deleter for a unique pointer that can be repeated

In C++, it is possible to use forward declaration to allow pointers to an incomplete type.
class A;
A *p;
However, in some cases I want to declare a unique pointer instead, so I use
class A;
class A_Deleter { void operator()(A*); }
unique_ptr<A, A_Deleter> p;
This is adequate in many cases, but has one major disadvantage. Unlike a real forward declaration, it cannot be written twice. I.e. while this code compiles:
class A;
class A;
This one doesn't:
class A;
class A_Deleter { void operator()(A*); }
class A;
class A_Deleter { void operator()(A*); }
How would you forward declare a deleteable class?
Why do you need to repeat it?
Put the declarations in a header (with proper include guards) and include it where needed.
What you can do is create a header specifically for the forward declaration, which also declares the deleter. Give the header the usual guards, and include that header instead of forward-declaring A.
But in general, I would go a different route. If I just need to declare the unique pointer, I would just forward-declare and do unique_ptr<A>. If I actually have a context where the unique pointer is destroyed, I would grab the full definition of A.
I think I found my solution.
I define a class visible through a header to everyone:
template <class T> class deleter { void operator()(T *x); };
I can then get rid of the need to declare the deleter class and can write things like this:
class A;
unique_ptr<A, deleter<A> > p;
The deleter<T>::operator() for each T can be implemented using specialization in its own .cpp file.

What does the statement class foo; mean

I have been going through the code of a project and have encountered the statement
class foo;
.
.
.
.
foo* f1;
in various places. The class has not been declared in any of the headers included either. Can anybody tell me what that means.
It is a forward declaration. It can be used for classes, structs and functions, and it tells compiler that this is defined elsewhere or later.
For classes, there are (at least) two use cases.
1. Full definition not needed
After forward declaration, compiler does not know size or members of class, only name. That is enough for pointers to the class (and references which are basically syntactic sugar around pointers). But often pointer is enough, and then you can avoid including entire header file in another. This helps compilation speed, by avoiding need to recompile everything when one header changes.
myfuncs.h
class MyClass; // forward declaration
void helpMyClass(MyClass &needy);
// here this would give compiler error about incomplete type:
//void badHelp(MyClass needy); // value needs definition
myfuncs.cpp:
#include "myclass.h" // entire MyClass definition
void helpMyClass(MyClass &needy) {
needy.helpMe(false); // needs full definition
}
Important use case for this is the so called PIMPL idiom, also well covered here at SO under pimpl-idiom tag.
2. Two classes need to refer to each others
class node; // forward declarion
class collection {
node *frist; // pointer enabled by forward declaration
}
class node {
collection *owner; // already defined above so works too
}
In this case forward declaration is required to make this work nicely. Just saying in case you see it in the wild, there's the ugly way of using void pointer and casts, sometimes used when novice programmer does not know how this should be done.
I think you're referring to a forward declaration. It tells the compiler that a class named foo will be defined later. Until then it is an "incomplete type", meaning that pointers and references to the class can be defined. Instances of the class cannot be created until it is fully defined.
Your declaration is incorrect? I'm not sure.. I do know that you can't have "any" space "name".. Perhaps you missed an underscore?
I believe you meant:
class foo any_name();
In that case, it's forward declaring a function called any_name that returns a class instance of foo.
Example:
#include <iostream>
class foo any_name(); //The forward declaration..
class foo //the foo class implementation.
{
public:
foo(){std::cout<<"hey";}
};
class foo any_name() //The implementation of the function..
{
std::cout<<"any_name";
//return {}; //Can be used to return a constructed instance of foo.
};
int main()
{
any_name();
}

Error: Pointer to incomplete class type is not allowed. How do I go about this?

So I have been stuck on this problem of sharing a function from one class to another and every solution I have found so far as not solved my problem.
One instance is here(I assure you there are others), [http://software.intel.com/en-us/articles/cdiag436]
Bar.h
#ifndef __Bar_h_
#define __Bar_h_
#include "BaseApplication.h"
#include <Foo.h>
class Foo;
Foo *foo;
class Bar : BaseApplication
{
public:
Bar(void);
~Bar(void);
protected:
virtual void barCreate(void);
};
#endif
Bar.cpp
#include "Bar.h"
#include <Foo.h>
Bar::Bar(void){}
Bar::~Bar(void){}
void Bar::barCreate(void)
{
if(foo->foobar()==true) //error: pointer to incomplete class type is not allowed
{//stuff}
}
Foo.h
#ifndef __foo_h_
#define __foo_h_
class Foo
{
public:
Foo(void);
~Foo(void);
bool foobar(void);
};
#endif
Foo.cpp
#include "Foo.h"
Foo::Foo(void){}
bool Foo::foobar(void){ return true; }
If I could get some pointers or explanation of where i'm going wrong that would be great.
You are misreading the error. It is not complaining about having a pointer to an incomplete type, but about dereferencing it.
if(foo->foobar()==true)
At this point the type of foo is an incomplete type, so the compiler cannot check whether it will have a foobar member function (or member functor).
Basically for an incomplete type you can declare and define pointers or references, declare interfaces (functions that take or return the type). But other than that you cannot create objects of the type, or use the pointers/references for anything other than copying the pointer/reference.
Regarding what you are doing wrong, you need to look to your real files in more details. Either you are not including the header that defines Foo, or you have multiple Foo types (different namespaces? one defines the type, another has the forward declaration) or your include guards are wrong and even if you include the header the guard discards the contents of the header. Note that after inclusion of the header that defines Foo you don't need to (and should not) provide a forward declaration of the type, as that can easily lead to multiple declarations of Foo in different contexts. If removing the forward declaration fails to compile, figure out why and fix that.