I'm working on a multiple inheritance project in C++. I have separate files for class definitions (.h) and implementations (.cpp). Since this is the first time I've used inheritance in C++ (the rest of our assignments have been in C#) somethings are a little unclear.
Do I need to #include "parent.h"
in child.cpp
, or is it sufficient to have defined the inheritance relationship in child.h
ie:
class child : parent
{
// child class definition
};
I was warned by an automated prompt that this might be a subjective question, so let me be explicit: I'm asking if this is a functional requirement for the inheritance to work properly, not if it's "good form" or anything along those lines.
Question
Do I need to
#include "parent.h"
inchild.cpp
, or is it sufficient to have defined the inheritance relationship inchild.h
Answer
No, you don't need to
#include "parent.h"
inchild.cpp
. It is sufficient to#include "child.h"
inchild.cpp
. The contents of"parent.h"
are available inchild.cpp
sincechild.h
already has#include "parent.h"
Just in case this isn't clear:
#include
does a simple textual copy, there is no additional logic involved.
So no, it is not necessary. However the reason is not that you have defined the inheritance relation ship, but because #include "parent.h"
in child.h
already copies the text of parent.h
into child.h
and then #include child.h
in child.cpp
, copies the whole text (including the part from parent.h
) there. Another include would be redundant, and without the include guards it would even cause compiler errors.
Btw.:Conceptually, your compiler doesn't see the headerfiles as separate entities. It sees only a single textstream, which is produced by starting with the cpp file and then executing (recursively) all #include directives.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.