C++, order of included header files in inheritance?
I've been trying to learn c++ and when learning inheritance i came up with this problem:
i have 3 files, mother, daughter and the main cpp. Mother and daughter have their respective header files. i included the daughter.h file in the daughter.cpp file as well as the mother header file. like this: Daughter.cpp Code:
#include "Daughter.h" saying: error: expected class-name before ‘{’ token daughter.h Code:
#ifndef DAUGHTER_H Code:
#include <iostream> So.. is there a rule on how to include header files that i am missing? |
Yes, you are missing something. In the Daughter.h header file, the class depends on Mother. Thus you should have included Mother.h within Daughter.h.
Mother.h: Code:
#ifndef MOTHER_H Code:
#ifndef DAUGHTER_H Code:
#include "Daughter.h" |
Quote:
I totally agree with you on the answer to this question of better programming style. But I think you may be confusing the OP by phrasing a better style answer as if it were a question of right/wrong. The original was wrong (not including mother.h from daughter.h and including daughter.h before mother.h in a cpp. The OP's change to fix only the sequence of include was not wrong, merely inferior style. Quote:
In your example, it needed the definition of Mother (before its use) and had neither the declaration nor definition. The header file sequence affects that rule indirectly by affecting the sequence in which the compiler reads things. But nothing about the real rule is specific to header files. I think, as a matter of good style, every single header file should be coded so that if it were the first header file some cpp file included then it would still be able to compile. In other words the header file includes anything it needs for itself and never depends on the thing that included it including anything else before it. |
All times are GMT -5. The time now is 02:50 AM. |