Where to put the enum in a cpp program? - c++

I have a program that uses enum types.
enum Type{a,b,};
class A
{
//use Type
};
class B
{
// also use that Type
};
2 class are located in 2 different files.
Should I put the type definition in a headfile or
in class definition for each class?

If the enum is going to be used in more than one .cpp file, you should put it in a header file that will be included by each. If there's a common header file, you should use that, otherwise you may as well create a new header file for this enum

You should always attempt to limit the scope of types in C++, so the enum should probably be declaread at class scope. The enum will typically belong slightly more naturally in one class than the other - lets say class A, so you put it in the declaration of A in the a.h header:
// a.h
class A {
public:
enum Type { a, b };
...
};
Now you need to include a.h in the header that declares B:
// b.h
#include "a.h"
class B {
public:
void f( A::Type t ); // use the Type enum
...
};

I can see the point of Neil: it is a pet peeve for many programmers to see stuff on the global scope. otoh, imho, introducing a class just for an enum is not a good style: It is supposed to be enum not a class. However, putting the same enum list in both classes (is what you were asking) would be the worst idea: we don't want to be repeating stuff.
Moreover, in most non-trivial codes, one might end up using more of such shared entities (more enums, const parameters, etc...) for implementation. So, I'd begin lumping all this into an implementation namespace (say "detail") which is a child namespace of your classes, and resides in a separate header file (say "detail.hpp"), included by all. For example:
// file A.hpp
#include "foo/detail.hpp"
namespace foo {
class A
{
// accessing enum as detail::a
};
}
// file B.hpp
#include "foo/detail.hpp"
namespace foo { class B { ... }; }
// file foo/detail.hpp
namespace foo { namespace detail {
enum { a,b, ... }
const int three = 3;
// etc...
// other implementation classes etc...
}}
And "detail" is nice and clean way of warning your class users to back off from whatever's declared in there. As your code gets bigger and these implementation details start growing in number you can break the dependencies into separate header files (detail1 detail2 etc...) and still keep one "detail" namespace (something which you can not do with a "class detail" for example).

The question is rather vague, but as a rule of thumb, you should try to minimize the redundancy in your code. Therefore, you should put the declaration of the enum to a header file.

It really depends on if the values are the same logical type, or if they just happen to have the same names. Would it make sense to assign an A::Type variable to a C::Type? If they are the same logical type, put them in a header that both include. To keep your build times low you probably want to put it in its own header file, but putting it in a shared header with other stuff works if you want to keep the number of files down.
Another option is to put the enum in a common base class that both inherit from (this may not make sense in this case, but it is another option).

Related

Resolving Inclusion Ordering

I am working on a codebase that is not my own, that has the following layout:
object.h:
// Objects are defined
// #include "tickets.h" (functions to access the objects)
// An access-handler object is defined
I want to introduce a class that knows about the objects, can be accessed from functions in tickets.h, but can also use the access-handler object. The functions are separate, i.e. class functions that are called in tickets.h do not use the access-handler (I wouldn't know where to start if that weren't the case).
Therefore my class needs to be defined before tickets.h, but some of its functions need to be defined after the access-handler. Is there a way to do this without splitting it up into two header files something like the following:
// Objects are defined
// -- include declaration of class, and definition of functions that tickets.h needs
// #include "tickets.h"
// An access-handler object is defined
// -- include functions of class that need the access-handler
This seems very messy splitting things up like this into two separate files, I was hoping to keep everything contained.
Thanks for any help, I clearly only have a very rudimentary understanding of declarations/definitions in c++.
EDIT: If I use forward declaration and include it before tickets.h (with the class declared in mynewclass.h and functions defined in mynewclass.cc) will mynewclass.cc be able to use objects declared after the inclusion of mynewclass.h? Namely the access-handler object.
EDIT2: Something like this:
object.h:
class obj { // definition }
#include "tickets.h"
class obj_handler {
public void handle { // code }
}
tickets.h:
void do_something(obj o){
communicator.foo();
}
My object (communicator):
class communicator {
public:
void foo() { // code }
void bar() { // use handle() from obj_handler }
}
As you can see, my communicator needs to be used in tickets.h, but can't be defined until after obj_handler. So where should I include it?
If I correctly understand your question - you can use forward declaration to solve this problem. This will allow you to declare some class before defining it's methods. For example:
// this is forward declaration of class A, no definition provided
class A;
class B
{
// uses A
A * a_;
};
// class A definition
class A
{
// may use class B now
B * b_;
};
I'm not quite sure whether I understand this right and don't have enough reputation here yet to make this a comment, so let me try to answer your question this way, please feel free to follow up if I'm guessing wrong:
I believe what you are referring to is an entire class definition, i.e., one including all function definitions within the class declaration. Other than that, it is not very common to see object definitions followed by preprocessor directives. What is typical though is a forward declaration of functions and a class prototype.
So, for example, you could declare in some header.h:
class C
{
public:
void method1(void);
int method2(void);
};
And in some implementation.cpp the definition of the functions like:
void C::method1(void) { /*...*/ }
In the other file preceded in the inclusion chain by your access-handler you then define the other function:
int C::method2(void) { /*...*/ }
What do you mean by access-handler, by the way?
Oh, and your linker likely will yell somewhat at you if you do function definition in a header file.
With regard to your addenda: everywhere you put a forward declaration, loosely speaking, the compiler will insert a copy of the declaration in question, consider it a soft link in the context of file systems. There are negative implications associated with it, like increased duration and the memory load of compilation if you have many forward declarations of the function signature or class. It's impossible to tell whether this will word in your particular situation since only you know the actual code in question. But most likely it would work.
Take a look at these pages:
http://en.wikipedia.org/wiki/Forward_declaration
When can I use a forward declaration?

Any reason not to #include from another file for numerous private class constant declarations in c++?

Is there any reason why one shouldn't #include another file from within a class declaration when that class defines numerous private constants?
I'm writing a class which adheres to a simple state-transition system and defines a processing schedule consisting of several states, each of which consist of a series of steps. Because the class has to refer to these states and steps in various functions (for example, when determining which processing to apply based on the current state and step), I end up defining a bunch of private enum's within the class's declaration to make the implementation readable (so I can refer to things like kStates_ModeTransition and kStateSteps_ModeTransition_PrepareNewSetup etc, rather than just using the raw integer values associated with these states and steps).
As the list of states and state-steps has grown longer, this collection of enum's has become a fairly long, awkward chunk of code in the middle of the class declaration, and I feel these constants are more connected to the implementation than the interface - a user of the class doesn't necessarily have to know about them. Is there any reason why I shouldn't move all of these enum's to another file and then just #include that file into the private section of the class declaration? I haven't encountered another situation where it seemed appropriate to use a #include within the body of a class, so I'm wondering if there's a better way to handle this or any particular reason such an #include would be bad form. Furthermore, is there any sensible standard file extension to use on such a file, used only for text insertion (it isn't really a header...)? Just .txt?
Thanks!
Edit: A bit more to see if one of the mentioned alternatives completely dissolves my dilemma:
Trying to stick only to the essentials, here's an example of my current structure
// Processor.h
class Processor
{
public:
Processor();
void Process( float* input, float* output, int numSamples );
private:
// List of possible states
enum
{
kStates_Default,
kStates_SettingChangeImmediate,
kStates_SettingChangeCrossfade,
kStates_SpecialProcessing,
kStates_NumStates
};
// Lists of steps for each state...
enum
{
kStateSteps_Default_PrepareInput,
kStateSteps_Default_CalculateIntermediateValues,
kStateSteps_Default_CalculateOutput,
kStateSteps_Default_NumSteps
};
// Imagine more lists for other states here, with comments...
// Becoming quite long...
// Private functions used in implementing various processing steps
// (some are used by multiple state-steps in varying ways)
void PrivateFunction1();
void PrivateFunction2();
// Some member variables here
};
This is used in a real-time processing context in order to better balance DSP load when performing block-processing tasks. In reality, this class inherits from a base class which handles the actual scheduling of calls to Process, updating the current state and state-step as needed. Process() then consists of a switch statement which performs certain processing functions and IO based on the current state and state-step of the object.
The values declared in the enums are used within Process() and other private member functions inside processor.cpp, and nowhere else. I've declared them as private member variables to scope them to within the class. Is there a way to declare them inside the .cpp and achieve the same scoping? These are all meant to be constant integers optimized away at compile time and are essentially being used as #define 's - I just don't want to use macros.
All includes are just text inclusion. Since the file you're including contains C++ syntax, it should have a C++ header extension (.h or .hpp or etc.).
You may not need to include it into the declaration (I could speak to this more certainly if you post some code) ... you could just include it into the implementation files, and declare any enum member variables as int ... using typedefs (aliases for int) if you want to give them descriptive type names. Or if you're using C++11, you can forward declare your enum types without defining them, and then you enum member variables will be typesafe, preventing assignment of the wrong sort of enum value.
As for your question of whether there's a reason why you shouldn't move the enums out of your class declaration into another file and include that file: one can always invent reasons not to do things, such as "our Coding Standards say never to include a file other than at top level, at the top of the file", but if such arbitrary reasons don't apply to you then no, there's no reason. Do what makes the most sense in terms of code maintainability.
Using an #include in the middle of a class is highly irregular and could cause problems. It's much better if you declare your constants in either their own namespace or class.
For instance, this is a bad idea:
class Foo
{
#include "foostuff.h"
};
The more typical pattern is:
#include "foostuff.h"
class Foo
{
void bar(int x = FooStuff::const_x);
};
Inside foostuff.h you'd be careful to namespace things so they won't collide with other parts of your application.
The C++ way of doing things encourages the re-use of constants between different parts of your application instead of using #define to create macros that, once expanded, have no particular association.
All "include" files should be either .h for plain C or .hpp for anything that requires a C++ capable compiler to interpret. Anything else is non-standard and will, at the very least, lead to scorn from anyone who has to maintain your code.
New C++11 enum class may be forward declared and real definition moved to implementation. That will clean the mess and reduce annoyance.
// Procesor.hpp
class Processor
{
public:
Processor();
void Process( float* input, float* output, int numSamples );
private:
// Type of possible states
enum class kState;
kState somethingDealingWithState( kState s );
};
// Processor.cpp
// List of possible states
enum class Processor::kState
{
Default,
SettingChangeImmediate,
SettingChangeCrossfade,
SpecialProcessing,
NumStates
};
Processor::kState Processor::somethingDealingWithState( kState s )
{
if ( s == kState::Default )
{
return kState::SpecialProcessing;
}
return kState::Default;
}
In the end, it seems the best way to achieve equivalent functionality while gaining the benefit of separating the enumeration details into the .cpp implementation file is to use a forward declaration of a struct within the private portion of the class, and to then define that struct to contain the desired enum's from within the .cpp file.
// Processor.h
class Processor
{
public:
Processor();
void Process( float* input, float* output, int numSamples );
private:
struct States; // Used to scope State enum to within class
struct StateSteps; // Used to scope StateStep enums to within class
// Other stuff...
}
// Processor.cpp
struct Processor::States
{
enum
{
Default,
SettingChangeImmediate,
SettingChangeCrossfade,
SpecialProcessing,
NumStates
};
}
struct Processor::StateSteps
{
enum
{
Default_PrepareInput,
Default_CalculateIntermediateValues,
Default_CalculateOutput,
Default_NumSteps
};
enum
{
SettingChangeImmediate_FirstStep,
// ... other state-steps...
};
};
Here's why I think this structure is best in this particular use-case:
All enum listings are moved to the .cpp file, out of the middle of the header as desired, and additional StateStep enums which contain the same values (say, counting up from 0) may be added into the definition of the StateSteps struct without disturbing the .h header (while we could add entries to a forward-declared enum class, we couldn't have repeats of the same value and would need to add another enum class to the header).
All of the enums are scoped within the private portion of the class as before (albeit within another struct as well).
Enums which are being used to define compile-time integer constants may remain anonymous and not strongly typed enum class constructs, which may mislead others as to how the enums are being used (in the current use-case, we WANT to be able to compare different stateStep enum values to the same integer currentStep, depending on the current state, as we could with the originally defined anonymous enums).
Previous answers helped get me to this conclusion, but I feel that this is a way which most closely duplicates the functionality of the original definitions while moving them out of the .h file!

c++ header files including each other mutually

I have two classes both defined in separate header files. Each file has a field that is type of other class. Now I included in header of each file the header of other file, but compiler is generating errors. What am i missing?
You cannot have each class have "a field that is type of other class"; that would be a recursive definition and not only the compiler would not be able to make any sense out of it, it does not even make logical sense.
Each class having a field that is type of the other class is the kind of impossibility that you only see in M.C. Escher drawings, or animations thereof, like this one:
B. de Smit and H. W. Lenstra - Source: escherdroste.math.leidenuniv.nl
based on Escher's "Print Gallery" Lithograph, 1956, see Wikipedia
One of the two fields will have to be a pointer, so as to break the recursive containment, and avoid the logical impossibility.
Which brings us to the next problem: if class B is to contain an instance of class A, then obviously, A has to be declared before class B, so that A is already known to the compiler when compiling B. But if class A is declared before class B, how can we declare a pointer to B in A? Class B is not known yet at the time that A is compiled! The answer to this is a special construct known as forward declaration which exists precisely in order to accommodate situations like this. A forward declaration of class B looks like this:
class B;
All it is telling the compiler is that there will be a class called B. It does not tell the compiler anything about the contents of class B, so there is very little we can do with it, but we can do one thing: declare pointers to B.
So, the full solution to the problem looks like this:
file "A.h":
/* This is called a "forward declaration". We use it to tell the compiler that
the identifier "B" will from now on stand for a class, and this class will be
defined later. We will not be able to make any use of "B" before it has been
defined, but we will at least be able to declare pointers to it. */
class B;
class A
{
/* We cannot have a field of type "B" here, because it has not yet been
defined. However, with the forward declaration we have told the compiler
that "B" is a class, so we can at least have a field which is a pointer
to "B". */
B* pb;
}
file "B.h":
#include "A.h"
class B
{
/* the compiler now knows the size of "A", so we can have a field
of type "A". */
A a;
}
You shouldn't include the header files inside the other ones, just include the header files in your source files.
In the headers you can use a forward declaration:
// In Class1.h
class Class2;
// In class2.h
class Class1;
Also you can protect against a file being included twice using the preprocessor:
// Class1.h
#ifndef __CLASS_1_H
#define __CLASS_1_H
// content
#endif
I know this is an old topic but maybe you are still interested in solution!
Actually in C++ you can use two classes recursively without using pointers and here is how to do it.
file: a.h
#include <b.h>
class A {
B<> b;
}
file: b.h
class A;
template<typename T = A>
class B {
T a;
}
file: main.cpp
#include "a.h"
A a;
and that's all!
of course this is just for curiosity :)
You probably want to use forward declaration, unless you actually want to put instance of each class in each other. In which case you shouldn't use anything.
If B can only exist within A, I seem to be able to create A and B without using a pointer. B has to simply forward declare A and not include it (avoiding the recursive inclusion).
In my case, a Document has a Section which gets a reference to its Document.
section.h
class Document;
class Section
{
public:
Section(Document& document) : document{document} {}
private:
Document& document;
};
document.h
#include "section.h"
class Document
{
public:
Document() : section{*this} {}
private:
Section section;
};
main.cpp
#include "document.h"
int main()
{
Document document{};
}
This code compiles with g++ and runs on Linux.
A (complex) set of ifdef might enable it for other cases, but I'm not sure about the readability...
Besides the possibility of forward declaration - if it seems that you need two classes mutually within the other it is out of my experience a sign for a mistake in the depth of inheritance.
Eather the classes are a kind of siblings and you should create a parent class for both.
Or you are trying to use a class that is in fact a parent class within one that should have a sibling from this parent class. Then you should create this sibling as a third class.

Where to store Class Specific named constants in C++

If you have a class that has some named constants, what is the best practive for storing the constants:
Option 1: Namespace in Class header
So in my class header I will have:
class myClass
{
...
...
};
namespace NamedConstants
{
const string Bucket = "Bucket";
}
Option 2 Member Constants
class MyClass { // this goes in the class
private: // header file
static const string Bucket;
...
};
... and in the class implementation file:
const string MyClass::Bucket = "Bucket";
I actually prefer Option 1, considering it to be cleaner: the variable name and value appear together. Also, if you give the namespace a good name then it can make code more readable when you use constants:
TrafficLight::Green
Does anybody see any issue with this method over Option 2?
If the strings are meant to be seen/used by users of the class, you wouldn't consider to make them private class members. So I conclude they are not meant to be seen/used by users of the class. But then it doesn't make sense to put them into the header at all.
If you put them into the class (or into namespace scope into the header), then all changes to their type and identifier will force clients to recompile their code.
If you put them into the class' implementation file, they are a private detail of the class' implementation and changes to them only force recompilation of the class' implementation.
If you put them into an unnamed namespace, they cannot collide with any other name:
namespace {
namespace NamedConstants
{
const string Bucket = "Bucket";
}
}
Option 1 could lead to a separate string object for every file which includes the header. So it depends among others on how scarce your resources are.

Is it possible to add an object of a class in the class header?

I was wondering if there is a way to put objects of a class in a header?
For example:
class MyClass {
} object;
If I made an object there and then include the header in more than one source file, I get an error of multiply defined symbols found. I am new so don't understand fully everything.
Also, I want to do something like object.function() inside of a different function which is a member of a different class how can I do that?
Assuming you want a single object, in the header file just declare the object:
extern blabla object;
and then in one source file define it:
blabla object;
As for calling a method on an object from a different class, that is perfectly fine as long as the method is public.
class foo
{
public:
void public_method();
private:
void private_method();
};
void some_other_class::method(foo &f)
{
f.public_method(); // this is fine
f.private_method(); // this is not okay, private_method can only be called from
// within foo
}
There's also a third visibility (protected), which comes into play once you start dealing with inheritance.
You can find ways to do it (see the other answers), but just don't do it. As you said, you are new to C++, so better learn the good practices, and when you need global objects - create them in the source (cpp) file.
Besides it, try to avoid using global objects at all, and define your objects inside the classes or functions.
It's not a good practice to put definitions in header files as this would result to the error you encountered. Although there are ways to get around this (extern, header guard), it should be avoided as much as possible. Just remember, put declarations in header files, definitions in source files.
About your second question note you can also call a static method using the :: operator and the class name (without an instance) :
void AnOtherClass::method()
{
TheFirstClass::static_method();
}
You could also make a use of the singleton pattern, if that fits your need in this case.
For your second question. You can always make a class object as a (private) member variable of the class you want to call object.function() from.
For example:
// File a.h, includeguards etc. left out for clarity
class A {
public:
void func();
};
// File b.h
#include "a.h"
class B {
public:
void func();
private:
A object;
};
// File b.c
#include "b.h"
void B::func()
{
object.func();
}
Hope that helps.