Including file known to already be included - c++

What's the convention when including a file you know is already included by another include?
Example:
Class Base is declared in "base.h" and has a few child classes. Base has a virtual method foo(Bar& bar) and therefore includes "bar.h". From a proper convention standpoint, should we include "bar.h" in the child classes as well, given that the child classes include "base.h", which includes "bar.h"?

Given that the declaration of a function only requires the parameters to be declared, you'll need to include the corresponding header. For known base classes or types of non-private data members the definition needs ro be included. Since everything else either only requires a declaration or is an implementation detail, you shouldn't rely on indirect headers being included.

One school of thought is that including both base.h and bar.h in child.h is better. Even though this is a virtual function dependency, including bar.h points future developer (who might not have an IDE) into the declaration without having to read base.h.
For non-virtual function, including both should be better imho, since another developer can change the content of base.h without having to worry about child.h's dependency on bar.h.

Related

Inheritance and Includes

Lets say I have 2 classes. One is BaseClass and one is DerivedClass, being a derived class of BaseClass. I need to be able to create objects of both classes in another file. By using an #include statement to include the derived class in the new file, I have access to the derived class directly and the base class indirectly (as the derived class includes it in its file). Is it better to use this method of indirect "access" to the base class, or would it be better to directly include it alongside the derived class in the file?
The general advice is include what you use.
If you are coding to an API specification, and that specification does not explicitly detail the base-derived nature of the classes, then any changes to that relationship may break the includes that the files you depend on use.
See here as well.
If you are certain the BaseClass will always the base to the DerivedClass, then there may be little need include both, but for clarity, I would go ahead and do it anyway, it shows your intent.
Including all needed headers instead of relying on transitivity gives has two advantages:
If your header files will be refactored, you will not need to change your cpp file.
It clearly identifies your intent for other developers.

What are the risks to massively forward declaration classes in header files?

For every pointer p1 of class class1, are there any risks we should consider by using a forward declaration of class1 instead of including class1 header file?
I can see only the advantage: The header file will have less size.
Forward declarations outside the control of the provider of the class are problematic! I’m working on a code base where a lot of forward declarations are used. While things are initially great the existence of forward declarations become a legacy:
Classes can’t be moved from one namespace to a different one. Without the forward declarations the name in the original namespace could be made an alias (typedef or using alias).
Classes can’t be turned into specialisations of class templates as is, e.g., useful when generalising a successful class.
Class templates cannot be forward declared by users as only the first declaration of a class template can provide default arguments.
Assuming the forward declarations are provided via a header under the control of the class provider/implementer (e.g., the implemented providing something akin to <iosfwd>) these problems are not relevant as there is a central place where the declarations can be changed. However, having users decide to declare entities becomes a legacy causing significant cost.
The approach to provision of declarations outlined above seems to have caused some confusion. I'll try to clarify. In my mind the unit of implementation is a component (which is based on John Lakos's notation of a component). A component defines one or more closely related classes and/or functions. The implementation of a component consists of multiple files:
A header file declaring all relevant entities which also defines entities which must be defined when using the component, i.e., user-accessible classes, enumerations, etc. are defined.
A header file only declaring relevant entities provided by the component (multiple related components may share one such header file; <iosfwd> is an example of such a header shared across multiple components).
An implementation file defining all entities [which are meant to be ODR-used] which are only declared in by the headers above.
At least one file with a test driver testing all entities defined by the component.
Users of a component which in some contexts only need to know about names in the component would include the declaration-only header. In no case would a user provide a declaration of a name in a component: all declaration of a name in a component are the responsibility of the provider/implementer of the component.
I can see only the advantage: The header file will have less size.
That's not exactly the point.
Let's assume you have a class declaration in a header file like
namespace MyNamespace {
class Baz;
}
class Foo {
public:
void bar(const MyNamespace::Baz & x);
};
and the definition in a separate translation unit as
#include "Baz.hpp"
void Foo::bar(const MyNamespace::Baz & x) {
// actually do something with Baz
}
and in contrast having everything included in the header file (and necessarily all dependent sources will be recompiled when Baz.hpp will be changed)
#include "Baz.hpp"
class Foo {
public:
void bar(const MyNamespace::Baz & x);
};
with the declaration, the 1st version might help to compile the code a little bit faster.
Especially if you have your own headers and class declarations, and if any of these are likely to be changed, you only want to recompile your translation units in the codebase, and not every source file that includes your type dependent header.
Note that forward declarations can be only used with references and pointers. Also header inlined code which dereferences to the forwarded type members cannot be used.

Why we need to copy-and-paste functions declaration into inherited class header

This is for C++.
Usually we have our function declaration in header file and definition in source file.
Say we have a class A with some functions:
//< A.hpp
class A
{
public:
virtual funcA();
virtual funcB();
}
And we want to have a class inherit from A and override its functions.
//< childA.hpp
class childA
{
virtual funcA();
virtual funcB();
}
Everytime we change the declarations of funcA() funcB(), we need to copy-and-paste the new declarations to the child classes header files. If the inheritance chain is long, it's quite bother.
I remember we don't have this problem with Object-C, do we?
You don't need to copy a member function declaration to the child class's header file unless you want to override it. In that case, I believe the main reason you're required to declare it is to inform anyone reading your header file that the child class is providing a different implementation. In principle, the compiler can figure it out automatically, but it could be a real pain for a human to do the same thing manually.
Note that in many cases, people reading your header files may not have access to the actual source code for the body (e.g., if it's a proprietary library that is delivered to them as compiled objects), so they can't just go look at the body to figure it out.
From the Objective-C article on Wikipedia:
Objective-C, like Smalltalk, can use dynamic typing: an object can be sent a message that is not specified in its interface.
http://en.wikipedia.org/wiki/Type_system#Dynamic_typing
C++, on the other hand, is statically typed. It's a stricter compile-time restraint.

Including headers just for private data in a .h file

I have a class defined in class.cpp and class.h. The class uses some structures/classes/types/whatever defined in stuff.h (and of course, stuff.cpp) for private members and methods. My main program is in main.cpp, which #includes class.h, but doesn't care about anything in stuff.h. If it makes a difference, class.cp is supposed to be loaded dynamically (.dll/.so).
I would ideally like to have the stuff.h only included in class.cpp and stuff.cpp linked only to this file, as they would just cause name-space pollution in main.cpp and extra bloat by being linked to the final program.
The problem is that I have to include stuff.h in class.h, since it's definitions are used in the private: part of my class, which is all in class.h. And since main.cpp brings in class.h, it also gets stuff.h!
I hope this was clear. In C# this can be solved by partial classes. How would I do this in C++?
You do that in C++ by using pImpl aka Opaque Pointers where the class you expose only have one attribute which is a partially defined struct (sometimes people uses void* instead, but to same efefct).
The partially defined struct, then is fully defined inside your stuff.cpp and everything works as you expect -- the only snag is that you need to make sure that you constructor and destructor new/delete the internal implementation, and you need to make special provisions in your copy constructor and and your assignment operator operator= -- most people opt for just make the copy constrctor and assignment operators private, so that the compiler will object if they are used.
Looks like you need Pimpl Idiom here. The main idea of Pimpl is that you forward declare class with implementation instead of including it's definition. This allows you to remove dependencies on implementation in header files, which usually results in compilation speed up, especially on large projects.

Forward Declarations and Includes

When working with a library, whether it be my own or external, there are lot of classes with forward declarations. The same classes also have includes as well depending on the situation. When I use a certain class, I need to know whether certain objects that the class uses, are forward declared or are they #include(d). The reason is I want to know whether I should be including both headers or just one.
Now I know it is fairly simple to check, just compile (or go through all the headers until you find the object in question either #include(d) or forward declared). But with large projects, a simple compile takes a long time, and going into each include file to check whether the class in question is being included or forward declared is tedious, especially if it is a few levels deep. To illustrate the problem further:
Class A is a Class B is a Class C
which has a pointer to Class Foo
I include Class A and want to know whether Class Foo is ready for use right away, or whether I have to do the following:
#include "ClassA.h"
#include "ClassFoo.h"
So, is there a quick and easy way to find out about this dependency without compiling or going into the depended headers? (one of the reasons I ask this question is because I want to eventually make an add-in for VS and/or stand-alone program for this if the functionality does not already exist)
Thanks!
In a source file you should not depend on what the other header files include.
You should explicitly include every type that your code depends on.
If you do not use a type (ie just passing a pointer or a reference around) then you don't need its definition so don't include its header file (The header file for the methods you are using should have at least a forwward declaration).
So in your particular instance it is hard to tell.
Is you source file explicitly uses any members from Foo then you need to include "ClassFoo.h" otherwise don't. There is no need to go digging around in header files (they may change anyway). Just check exactly what your source file uses and include those (and only those) header files.
In the header file: Prefer forward declaration to inclusion. This way you limit/break circular dependencies.
Actually I am finding eliminating as many header includes as is humanly possible actually helps hella more. See this answer. By cutting out more #include statements, its much more clear exactly what is part of the source file (#includes are a blackbox - you never know what is getting linked in by that one line of text). If a class Foo needs the implementation details of a class Bar, then Foo.h should not include "Bar.h", but rather, contain only a forward declaration. Foo.cpp should include Bar.h.
Foo.h
class Bar ; // fwd declare wherever possible
class Foo
{
// I can haz needs Bar
void do( Bar *bar ) ;
} ;
Foo.cpp
#include "Foo.h"
#include "Bar.h" // I can has needs complete implementation details.
Foo::do( Bar *bar )
{
}
Bar.h
class Bar
{
// code..
} ;
If you're using class A then you should only care about the private interface of the base class C (and possibly additional interface in A. If the class is designed properly, you won't need to access Foo directly because it will be encapsulated in C's interface and not exposed to the public world. In this case you won't need an include to Foo at all because it's not part of C's public interface. If in fact Foo is part of the interface to C in some way, then I argue that C.h should include Foo.h as well, so that clients can use it without having to make the determinations you're asking about.