Reputation: 29
If i include a base class in a different class, will that base's derived classes be included also. If i include lets say a shape class, and that class is a base class for the derived classes square and circle, will square and circle be included in that different class.
I want to do this, so if i decide to add another shape class later on(call it diamond), it will be easier writing...
#include <shapes.h>
rather than...
#include <square.h>
#include <circle.h>
#include <triangle.h>
Upvotes: 1
Views: 252
Reputation: 1143
No, the header files for the derived classes will not be included automatically. However, the good news is that in most cases you probably won't need to include the header files for the derived classes at all - the code responsible for creating the different shape objects needs to know about circles and triangles, but in most cases the code that (for example) draws the shapes can simply call a virtual draw
function that will do the right thing for whichever kind of shape it happens to be given. Virtual functions are implemented in such a way that calling shape's draw
function will correctly call the overridden versions for circle and triangle even if the header files for those classes aren't included in the file where the call is made.
If you find that your code regularly needs to know if something is a circle or a triangle (and hence needs to include the header files), that probably points to a problem with the shape class' interface. In that case, you should take another look at shape and see if you can change it in a way that you can call virtual functions and let the compiler sort out which is the correct implementation for each shape.
For the more general problem of having a whole bunch of header files that you often want to include together, you can make life easier by creating a single header file that includes all of the others. For example, you might create shape_library.h
and put #include
s for all of the different shape headers in there. That way, everything else can just include shape_library.h
, and you only have one place to change if the headers get rearranged.
Upvotes: 1
Reputation: 139
No, it won't.
When you do #include<a.h>
, the preprocessor recursively inline the content in a.h here.
So in your case you will only get the base class.
Besides, it is not a good idea to do this(include .h where base class is in and get all derived classes).
If you do that, maybe one day you only want to create a class derived from the base, you include all derived classes which are not used at all, increasing the code size.
Upvotes: 3