Why must a subclass' using statements be duplicated? - c++

Relatively new to cpp. When you subclass a baseclass, the #include cascade to the subclass, why don't the class-wide usings in the cpp file also cover the scope of the subclass? Is this a historical or pragmatic reason? Err.. What is the reason?
//available to subclass
#include <cinder/app/appBasic.h>
// have to duplicate in subclass
using namespace ci;
using namespace ci::app;
using namespace std;

using directive and using declaration are only valid for the current translation unit. you can put these in the header file which is not a good practice.

The main reason is that the compiler only looks at one .cpp file plus whatever it #includes. It has no idea what using statements there might be in the .cpp file for your base class. For that matter, it has no idea whether you've even written the .cpp file for the base class yet when you compile the .cpp file for the derived class. And it's not going to go rooting around the filesystem to find out, unlike for example javac.
Furthermore, I guess you're writing one .cpp file per class, and giving the file a name that has something to do with the class name. But C++ doesn't require that. You can have more than one class in a file, or for that matter you could split a class across multiple files if you want to.
So, you know that this .cpp file is the file for your derived class, and that the other .cpp file is the file for the base class, and therefore you think it might be convenient if some stuff from the other .cpp file was lifted into this .cpp file. But the compiler knows no such thing. It wouldn't make sense to the C++ compiler to talk about what's in the file for the base class.
Finally, a reason that is principled rather than pragmatic: just because it is convenient for the implementer of the base class to bring the names from certain namespaces into global scope doesn't mean the same will be true of the implementer of the derived class. The derived class might not use ci::app at all, let alone use it so much that the person writing the derived class is sick of typing it. So even if C++ could require the compiler to fetch those using statements (which, given the compilation model, it can't), I'm pretty sure the language's designers wouldn't want it to.
the #include cascade to the subclass
No they don't. Any #include in the base.h will be included into derived.cpp if (for example) derived.cpp includes derived.h which includes base.h. But any includes in base.cpp have no effect on derived.cpp.
This is all assuming that you follow the usual naming convention. There's nothing other than convention to stop you including a .cpp file from derived.cpp, in which case (1) any includes or using statements would apply in derived.cpp, but unfortunately (2) you'll probably break your build system, because most likely you won't be able to link base.o and derived.o together any more on account of them containing duplicate definitions for code entities subject to the One Defintion Rule. That is, functions.

Related

Do I need a .h for a class with only a main method in C++

I need to create 2 classes, with their respective .h and .cc, and then another class with a main, let's call them A, B and C, being the C class the one with the main.
Given that the C class is used only to contain that main and doesn't need either instance or class variables, or other methods, do I need to create C.h or with C.cc it's enough?
Well technically, you don't need headers ever, you could simply copy-paste declarations in every .cpp files.
If you don't need a declaration in any other file, I'd suggest this is a good practice to place it in the relevant .cpp file to keep it private. This can be couple with a namespace { ... } or declare them as static (static as in private to translation unit). This hides irrelevant details from your header code, and prevent misuse of private functions and private variable that should only be used in one .cpp file.
C.cc should be enough, since you are not doing any variable declarations in that class.
You just need to include A.h and B.h through #include statements
It's a good habit for organizational purposes. If your intention is to use them together as a library for the next program you build, then yes, you should, that way you'll run in less compiling issues.

C++ Including header file multiple times

I was just wondering where is it necessary/right to include a specific header file according to the example below. Let's assume I have a definition of an exception class:
//exc.hpp
#ifndef EXC_H
#define EXC_H
class MyException : public exception {
};
#endif /* EXC_H */
Then I have another class definition throwing such exception:
//a.cpp
void SomeClass::someMethod(void) {
throw MyException(...);
}
And having another file handling that exception, e.g.:
//main.cpp
#include "a.hpp"
int main() {
...
catch(MyException & e) { ... }
}
So my question is, where should I place #include "exc.hpp"? Just to a.hpp, or both a.hpp and main.cpp?
And when it comes to makefile... How should be the targets specified within such file?
Every translation unit that throws or catches exceptions of that type will need to be able to see its definition.
Loosely speaking, that means every .cpp file containing a throw or catch relating to that exception must include your .hpp file.
That's even if you only catch by reference and never inspect the exception object, which is not the case in other areas of C++ (where a forward declaration will do).
Makefiles are unrelated.
Both the file with implementation (a.cpp) and all files the use the class (main.cpp) should have the #include.
a.cpp without the include must not compile at all.
You need to include the .hpp file in both main.cpp and a.cpp. The purpose of the #ifndef sequence is to prevent accidental multiple inclusion (through indirect #includes). There is also a #pragma once directive in MS compilers that does the same thing.
The compiler figures out what .h/.hpp files to read based on the #includes in the .cpp files; the make file is not involved.
Remember that the compiler processes each source file independently, and doesn't remember anything from the source file once it's done processing. Even if you list several source files on a single compiler command-line.
You have a header-file that defines a type. Naturally, you must #include the header file in every source file where you need that type to be defined. (The compiler will not remember having seen the types when processing earlier source files.)
It might be tempting to #include headers within other headers, just so you don't have to #include so many things within the .c or .cpp files, but this should be avoided to the degree possible. It produces what is known as "header coupling", and it makes code that is hard to re-use later on other projects.
There's also a fine point hiding in what I said above: "where you need that type to be defined". There are two very specific concepts in C and C++ related to variables:
declaration -- when you make the compiler aware that a type exists, and
definition -- where you tell the compiler the details of the type.
You need to #include your header wherever you need the definition. I.e., when you intend to instantiate an object of the type, define members of the type in another struct or class, or call one of its methods (assuming C++). If instead, you only want to store a reference to objects of the type without creating or using them, a declaration will suffice, and you can just forward-declare the class. I.e.,
class MyException;
void setFileNotFoundExceptionObject(const MyException *exc) { ... }
Many APIs are designed specifically around only using pointers or references to objects so that the API headers only need forward delcarations of the types, and not the complete definitions (This keeps the internal members of the objects hidden to prevent developers from abusing them.)

Importance of declaring variables and functions in header file

I declare all variables and functions in .h file and has become my habit to do that (I'm programming with cocos2dx)
And I read that you should try to include the least in .h file and the most in .cpp file.
Because I declare all variables and functions in .h file, If I need to use another class from another file, then I need to include that class in the .h file to declare that class as a variable.
So I want to know the importance of declaring variables in .h file and .cpp file. I want to know which way is most standard as well.
If there is no difference, then why people would declare variables and functions in private file because declaring a function in .h file requires you to write it again in .cpp file.
ie)
.h file:
class classA {
private:
void function();
};
.cpp file:
void classA::function() {
...do something...
}
What is the importance of declaring variables and functions in header files?
Declare anything that is needed outside of the code in the .cpp file in the header file, and no more. Try to minimise the amount in there as much as possible. The reason for this is that other programmers could be looking at your header (.h) file, it is essentially their API. As an OOP programmer you want to hide as much of the internal workings of your objects as possible i.e. you do not want people using your API to become dependent on factors that may change as the structure of the objects does. Also try and keep the scope of your variables as low as possible. It is better to avoid global variables if you can in general. Passing them as parameters is almost always a better idea. Try to keep variables in the lowest scope possible.
Typically you would have your declarations inside a header file, and your definitions inside the cpp. There are many benefits to doing this, one of the biggest being re-usability. If you have multiple files that need to use a certain class, it is much easier to just include it where needed rather than having to re-declare it.
Being able to separate prototypes from the actual member bodies is also quite useful. This allows you to do things such as having a binary version of the implementation, and still keep the function names publicly available. This way if someone was using your class or library they could see how to use it, but not be able to see how it actually works. This is very important in larger projects and when copyright is involved.
This is a good habit to get into, but can get confusing and overwhelming if you don't stay organized. Common practice is to have an implementation file (.cpp) and a header (.h) for each class, both generally having the same name as the class to improve readability.
You should avoid using a header file just to declare local variables as it's generally best to keep them in the scope where they're needed.
As for your particular sample, you can avoid putting class private methods into the header file using the Pimpl Idiom. You'll have only publicly visible (public/protected) members declared in your header file, all the rest goes to the .cpp:
.h file:
class ClassA {
public:
ClassA();
~ClassA();
void foo();
private:
class ClassAImpl;
ClassAImpl* pImpl;
};
.cpp file:
#include "ClassA.h"
struct ClassAImpl
void function() {
// ...do something...
}
};
ClassA::ClassA()
: pImpl(new ClassAImpl()) {
}
ClassA::~ClassA() {
delete pImpl;
}
void ClassA::foo() {
pImpl->function();
}
Benefits of having a separate .h and .cpp file
Hide Implementation: You can separate the declaration from definition. So say you want to create an API, you could put your actual logic in .cpp (which becomes the library file on compilation) and have the declaration in .h which someone one could use to access the API.
Reduce Compilation time: One benefit of having definition in .cpp and declaration in .h is when you want to make changes to the definition. Such a change, would just change the cpp file and that .cpp will have to be recompiled. If the definition were to be in .h file, all the .cpp files where the .h file is included would have to be recompiled which would take more time.
Improves Readability: Having declaration and definition separate in some ways improves readability.
One of the reasons we have separate header and source files in C++ is because C++ code is unmanaged . It is directly executed by the processor (unlike C#, Java which are executed in a virtual environment). This requires having a header file to hold the symbol information which while being separate from the implementation, acts as an interface to it.
In C and C++, the order in which things are declared is important. Remember that when these languages were designed - compilers were not what they are today. Header files are things that you "include" which describe classes, type-definitions, enums. Now, you can provide implementation (and in the case of C++ template classes, you have to) in the header file. You put the implementation of the stuff in to the .cpp file. You're not writing a function twice (the compiler will have a hissy-fit if you do). You declare or implement them in the header file and then, in the case of the former, you implement them in the C++ file.
Consumers of your code (in a library project, for example), will include the header files (that describe the classes), and then link against an object file (as opposed to .cpp files). Header files provide you, ahead-of-time, the symbols to expect and link against.
Templates are a little weird in this respect (you don't export them), they are header file only (at the moment, I believe).
Modern languages such as C# do not have the concept of header files, because of the way the compiler works. The C# compiler looks at the files as a "whole" and therefore there is no need to forward declare anything or worry about header files. C/C++ compilers do not do this. I am unsure (without going and looking it up) whether or not this was due to compiler technology at the time or a concsious design decision at the time.
You are not duplicating code.

C++ include header problem

I am new to c/c++, I am confused about followings:
Whether I should put class declarations in its own header file, and actual implementation in another file?
Whether I should put headers like <iostream> in the example.h file or in example.cpp file?
If all the classes need to use <iostream>, and I include a class's header file into another class's header, does it mean I included <iostream> twice?
If I use a lot STL classes, what is a good practice to use std::?
1.Whether I should put class declarations in its own header file,
and actual implementation in another
file?
You can write the definition of a class, and the definition of the members of the class separately in the same header file if you are manipulating templates. Also, if you want to make your members function inline, you can define them inside the class definition itself. In any other case, it is better to separate the definition of the class (.hpp file) and the definition of the members of the class (.cpp).
2.Whether I should put headers like in the example.h file or in example.cpp
file?
It Depends on if you need those headers in the example.h file or in your .cpp file only.
3.If all the classes need to use , and I include a class's header file into
another class's header, does it mean I
included twice?
It happens if you don't wrap your class definitions by the following macros:
#ifndef FOO_HPP
#define FOO_HPP
class {
...
};
#endif
5.If I use a lot STL classes, what is a good practice to use std::?
I think it is better whenever you can to use std:: each time instead of using namespace std. This way you will use only the namespaces that you need and your code will be more readable because you will avoid namespace conflicts (imagine two methods that have the same name and belong to two different namespaces).
But most importantly where is question number 4 anyway?
Generally, yes. It helps with organization. However, on small projects it may not be that big of a deal.
I'm having trouble understanding the question here. If you're asking where to put the #include directive, the implementation file should include the header file.
Yes, but the use of include guards prevents multiple inclusions.
You normally should, but for relatively small projects you may avoid having an implementation file as much as possible;
If your header is using only incomplete types from the <iostream>, you can avoid including it, but you'll need forward declarations for these types (see When to use forward declaration?). Yet, for simplicity, if the type uses template, I normally include the respective header;
No. The include guards guarantee that a header is included only once in the same translation unit;
A common good practice is to not put using namespace std in a header file. Be aware of namespace conflicts too;
Typically, you do put class declarations (including declarations of members) into header files and definitions of member functions (methods) in source files. Headers usually have names like *.h or *.hpp. As to point 3, you should put include guards into your headers so they can be safely included multiple times in the same source file; then you can include them everywhere you need them. I don't understand point #5: are you asking about when to use std:: namespace qualification?
For the "included twice" problem, here is a common pattern for your header files:
// _BLAHCLASS_H_ should be different for each header, otherwise things will Go Bad.
#ifndef _BLAHCLASS_H_
#define _BLAHCLASS_H_
... rest of header ...
#endif
As long as they're not templates, generally yes. Templates (for better or worse) have to be put in headers.
I prefer to make each of my headers "standalone", so if any other header is needed for it to function, it includes that header itself (e.g., if I have a class that uses std::string, the header for that class will #include <string>.
No. With a few special exceptions, the standard headers are required to be written so you can include them more than once without it changing anything (the primary exception is assert.h/cassert, which it can make sense to include more than once).
I'm not sure exactly what you're asking. If you're asking about a using directive like using namespace std;, then it's generally (though certainly not universally) disliked. A using declaration like using std::vector; is generally considered less problematic.

A basic understanding of C++ header files

I have a theory question rather than an error report.
I'm a rookie C++ programmer, trying to promote that away
Using the VC++ VS2008 compiler
I am often finding myself wondering WHY I want to take some actions in header files.
For example look at this code block:
#include "DrawScene.h"
#include "Camera.h"
#include "Player.h"
#include "Grid.h"
#include "InputHandler.h"
#include "GameState.h"
class Controller
{
public:
private:
public:
Controller();
~Controller(){}
void Update();
private:
};
And the hooked up CPP file , controller.cpp along with it
#include "stdafx.h"
#include "glut.h"
#include "Controller.h"
#include <iostream>
Grid* grid_ptr = new Grid();
InputHandler* inputHandler_ptr = new InputHandler();
DrawScene* drawScene_ptr = new DrawScene();
GameState* gameState_ptr = new GameState();
Controller::Controller()
{
}
void Controller::Update()
{
}
What is a good way to decide which includes go where? So far I've been going with the " whatever works" method but I find it somewhat unprofessional.
Now even though you can say my code has X syntax errors and design flaws, please do, but the focal point I would appreciate that information remains on the use of .h VS .cpp files.
Why is there even such a design? And what are the pits and traps to always be treading lightly around when making any kind of OOP based C++ program?
What sparked this question for me btw was that I wanted to notify the reader of the header file there will be objects stored in the controller but assigning these uninitialized objects seemed impossible without making them static.
Note: I stem from C# --> C++ , might help to know. That's kind of my perspective on code at this point.
Thank you in advance for you efforts!
EDIT: 26/08/2010 18:16
So the build time is the essence of good includes. Is there more to be cautious about?
This is my personal opinion rather than a consensus best practice, but what I recommend is: in a header file, only include those headers that are necessary to make the contents of the header file compile without syntax errors. And if you can use forward declarations rather than nested inclusions, do so.
The reason for this is, in C++ (unlike C#, iiuc) there's no export control. Everything you include from a header will be visible to the includers of the header, which could be a whole lot of junk that users of your interface should not see.
Generally speaking headers should reside in the cpp file. For standard library includes (and possibly 3rd library includes) you can stick them in headers. However headers defined specifically for your project should go in cpp files whenever possible.
The reason for this is compilation time and dependency issues. Any time you change a header file, the compiler will have to recompile every source file that includes it. When you include a header file in another header file, then the compiler has to recompile every cpp file that includes either header file.
This is why forward declaration and the PIMPL (Pointer to IMPLementation, or opaque pointer) pattern are popular. It allows you to shift at least some of the changes/implementation out of the header file. For example:
// header file:
class SomeType;
class AnotherType
{
private:
SomeType *m_pimpl;
};
doesn't require you to include "sometype.h" whereas:
// header file
class AnotherType
{
private:
SomeType m_impl;
};
does. EDIT: Actually, you don't need to include "sometype.h" in the "anothertype.h" if you ALWAYS include "sometype.h" before "anothertype.h" in EVERY cpp file that includes "anothertype.h".
Sometimes it can be difficult to move a header file to the cpp file. At that point you have a decision - is it better to go through the effort of abstracting the code so you can do so, or is it better to just add the include?
Only include headers in another header if absolutely necessary. If the header can go solely in the source file then that's the best place. You can use forward declarations of classes in the header if you are only using pointers and references to them. Your DrawScene, GameState, Grid and InputHandler classes looks like they might fall into this category.
Note that C++ as a language does not care about the distinction between headers and source files. That's just an extremely common system used by developers to maintain their code. The obvious advantage of using headers is to avoid code duplication and helps, to an extent, to enforce the one-definition-rule for classes, templates and inline functions.
Avoid putting too many (read, any unnecessary) #includes in your .h file. Doing so can lead to long build times, as e.g. whenever you change Camera.h you will have changed Controller.h, so anything that includes Controller.h will need to be rebuilt. Even if it is only a comment that has changed.
Use forward declarations if you are only storing pointer members, then add the #includes to the cpp file.
Theoretically, .h files contain just the interface, and .cpp files, the implementation. However, since private members are arguably implementation, and not interface, this is not strictly true, hence the need for forward declarations in order to minimise unnecessary rebuilds.
It is possible, in C++, to include the whole implementation inline in the class definition, file, much as you might with Java, but this really breaks the .h/.cpp interface/implementation rule.
Header files contain declarations of functions, classes, and other objects, whereas cpp files are meant for implementing these previously declared objects.
Header files exist primarily for historical reasons. It's easier to build a C++ compiler if the definitions of all functions, classes, etc to be used by your code are given before you actually call them.
Usually you use cpp for your implemenation. Implementing functions in header files automatically inlines them, so unless these are very small and / or very frequently called, this is usually not what you want.