Reputation: 2133
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?
Upvotes: 3
Views: 820
Reputation: 30605
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.
Upvotes: 5
Reputation: 19043
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.
Upvotes: 3