Using int in a header file? - c++

I have been working on a header file for the past couple hours and am having an issue outputting a value that is stored in the constructor. The value is an int but it won't let me store any number above 7 and when I output it using a function it comes out a totally different number. I am doing this all within a header file and using a function in the .cpp to output the data. I'm fairly new to C++ so it's probably an amateur mistake. Any help would be appreciated!!
Header File ----
#ifndef PATIENT_DEMO_CLASS
#define PATIENT_DEMO_CLASS
// system defined preprocessor statement for cin/cout operations
#include <iostream.h>
// programmer defined preprocessor statement for setreal operation
#include "textlib.h"
// programmer defined preprocessor statement for String
#include "tstring.h"
class PatientDemographicInformation
{
private:
int patientDateOfBirth;
public:
// constructor
PatientDemographicInformation(int dateOfBirth);
// returns the patient's age
int getPatientAge( );
};
PatientDemographicInformation::PatientDemographicInformation(int dateOfBirth)
{
patientDateOfBirth = dateOfBirth;
}
int PatientDemographicInformation::getPatientAge( )
{
return patientDateOfBirth;
}
#endif
.cpp ----
#include <iostream.h>
#include <tstring.h>
#include "PatientDemographicInformation.h"
int main( )
{
PatientDemographicInformation john(11161990);
cout << john.getPatientAge() << endl;
return 0;
}

Pure guess, here.
In C, C++ and many other languages, integers written with a leading 0 are octal; that is, they are in base 8 rather than base 10.
If you're doing something like:
dateOfBirth = 070503;
then that will be interpreted as an octal number (28995 in decimal). Since octal numbers can only have digits 0-7, the following will be illegal:
dateOfBirth = 090503;
I suggest you don't encode dates in this form, if that's what you are doing.

Related

char variable has not been declared

I have ran into a problem yesterday when trying to split my code into several files.
Yesterday morning my whole code was in one file and to keep track of everything more easily I wanted to split the code into more files.
This went well until I got to a function where I need to declare a variable although I already have (but maybe in the wrong place).
Because the code is too long, I have put all files to pastebin.
I have declared "field" in main.cpp:
char field[20][41];
Whole file here: https://pastebin.com/Jy1XvdpL
And I want to use this in my field.cpp:
void loadLevel(int levelnumber) {
// concatenate leven base with level number
std::string level = "level" + std::to_string(levelnumber) + ".txt";
// print field
// load the text file
std::ifstream file;
file.open(level);
char c;
// read line by line, character by character and store it in field
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 41; j++) {
file.get(c);
field[i][j] = c;
}
}
file.close();
}
The field.h looks like this:
#ifndef field
#define field
#include <iostream>
#include <string>
#include <fstream>
void loadLevel(int levelnumber);
void drawField();
#endif // !field
The problem is that I do not know, where to define char field because I get an error if done in either of these files. So what do I need to do to get char field workin in field.cpp and therefore work in my main?
P.S. This is my first program in c++ and I am learning new things everyday. I appreciate any hints on how to do certain things better ^^
Kind Regards,
Benjamin
When you declare a variable in your main file, you are not able to use it in another file. (or at least easily)
if you wish to use your field variable in the field.cpp, then you can define it in field.h.
Code for this could be as followed.
#ifndef field
#define field
#include <iostream>
#include <string>
#include <fstream>
void loadLevel(int levelnumber);
void drawField();
char field[20][41];
#endif // !field
Though this will not allow you to use the information you assign to field[i][j] will not be available in your main file.
To do this I would make a function in field.h and field.cpp that returns the value of field[i][j].
You can use field array in your function by passing it as an argument to your loadlevel function, check this question too if you want to use pointers.
So your function will look like:
void loadLevel(int levelnumber,char field[][41]);

How to make a variable available to multiple .cpp files using a class?

This question has derived from this one.
I have a working program which must be split into multiple parts. In this program is needed to use a variable (now it's a GTK+ one :P) many times in parts of the program that will end up in separated .cpp files.
So, I made a simple example to understand how to make variables available to the program parts. A modified version of the previous code would be:
#include <iostream>
using namespace std;
int entero = 10;
void function()
{
cout<<entero<<endl;
//action1...;
}
void separated_function()
{
cout<<entero<<endl;
//action2...;
}
int main( int argc, char *argv[] )
{
function();
separated_function();
cout<<entero<<endl;
//something else with the mentioned variables...;
return 0;
}
It is needed to split the code correctly, to have function(), another_function() and main() in separated .cpp files,and make entero avaliable to all of them... BUT:
In the previous question #NeilKirk commented:Do not use global variables. Put the required state into a struct or class, and pass it to functions as necessary as a parameter (And I also have found many web pages pointing that is not recommended to use global variables).
And, as far I can understand, in the answer provided by #PaulH., he is describing how to make variables avaliable by making them global.
This answer was very useful, it worked fine not only with char arrays, but also with ints, strings and GTK+ variables (or pointers to variables :P).
But since this method is not recommended, I would thank anyone who could show what would be the correct way to split the code passing the variables as a function parameter or some other method more recommended than the - working - global variables one.
I researched about parameters and classes, but I'm a newbie, and I messed the code up with no good result.
You need to give the parameter as a reference if you want the same comportement as a global variable
#include <iostream>
using namespace std;
// renamed the parameter to avoid confusion ('entero' is valid though)
void function(int &ent)
{
cout<<ent<<endl;
++ent; // modify its value
//action1...;
}
void separated_function(int &ent)
{
cout<<ent<<endl;
++ent; // modify its value again
//action2...;
}
int main( int argc, char *argv[] )
{
int entero = 10; // initializing the variable
// give the parameter by reference => the functions will be able to modify its value
function(entero);
separated_function(entero);
cout<<entero<<endl;
//something else with the mentioned variables...;
return 0;
}
output:
10
11
12
Defining a class or struct in a header file is the way to go, then include the header file in all source files that needs the classes or structures. You can also place function prototypes or preprocessor macros in header files if they are needed by multiple source files, as well as variable declarations (e.g. extern int some_int_var;) and namespace declarations.
You will not get multiple definition errors from defining the classes, because classes is a concept for the compiler to handle, classes themselves are never passed on for the linker where multiple definition errors occurs.
Lets take a simple example, with one header file and two source files.
First the header file, e.g. myheader.h:
#ifndef MYHEADER_H
#define MYHEADER_H
// The above is called include guards (https://en.wikipedia.org/wiki/Include_guard)
// and are used to protect the header file from being included
// by the same source file twice
// Define a namespace
namespace foo
{
// Define a class
class my_class
{
public:
my_class(int val)
: value_(val)
{}
int get_value() const
{
return value_;
}
void set_value(const int val)
{
value_ = val;
}
private:
int value_;
};
// Declare a function prototype
void bar(my_class& v);
}
#endif // MYHEADER_H
The above header file defines a namespace foo and in the namespace a class my_class and a function bar.
(The namespace is strictly not necessary for a simple program like this, but for larger projects it becomes more needed.)
Then the first source file, e.g. main.cpp:
#include <iostream>
#include "myheader.h" // Include our own header file
int main()
{
using namespace foo;
my_class my_object(123); // Create an instance of the class
bar(my_object); // Call the function
std::cout << "In main(), value is " << my_object.get_value() << '\n';
// All done
}
And finally the second source file, e.g. bar.cpp:
#include <iostream>
#include "myheader.h"
void foo::bar(foo::my_class& val)
{
std::cout << "In foo::bar(), value is " << val.get_value() << '\n';
val.set_value(456);
}
Put all three files in the same project, and build. You should now get an executable program that outputs
In foo::bar(), value is 123
In main(), value is 456
I prefer to provide a functional interface to global data.
.h file:
extern int get_entero();
extern void set_entero(int v);
.cpp file:
static int entero = 10;
int get_entero()
{
return entero;
}
void set_entero(int v)
{
entero = v;
}
Then, everywhere else, use those functions.
#include "the_h_file"
void function()
{
cout << get_entero() << endl;
//action1...;
}
void separated_function()
{
cout << get_entero() << endl;
//action2...;
}
int main( int argc, char *argv[] )
{
function();
separated_function();
cout<< get_entero() <<endl;
//something else with the mentioned variables...;
return 0;
}
If you do not plan to modify the variable, it is generally ok to make it global. However, it is best to declare it with the const keyword to signal the compiler that it should not be modified, like so:
const int ENTERO = 10;
If you are using multiple cpp files, also consider using a header file for your structures and function declarations.
If you are planning on modifying the variable, just pass it around in function parameters.

State Machines, Sub-Classes, and Function Pointers

I'm having trouble implementing a state machine for class. I keep getting the errors:
state.cpp:5: error: have0 was not declared in this scope
state.cpp:10: error: redefinition of State* Have0State::process(std::string)
state.h:18: error: virtual State* Have0State::process(std::string) previously defined here
I'm trying to get the Have0State to work before I continue onto the rest of the machine, hence the sparse code.
state.h:
#ifndef STATE_H
#define STATE_H
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <iostream>
class State{
public:
State(){};
virtual State* process(std::string input) = 0;
};
class Have0State: public State {
public:
Have0State():State(){};
virtual State* process(std::string input);
}have0;
#endif
state.cpp:
#include "state.h"
using namespace std;
State *currentState = &have0;
State* Have0State::process(string input){
if(input == "quarter"){
cout << "cool" << endl;
}
return &have0;
}
int main(int argc, char** argv) {
string input;
//get input
cin >> input;
while (input != "exit") {
currentState = currentState->process(input);
//get input
cin >> input;
}
return 0;
};
I've tried defining the process function as Have0State::State::process(string input) but that didn't work either. Any clarification on how function pointers are supposed to work, especially in the context of subclass member functions, I would greatly appreciate it.
EDIT: Also, what exactly is the have0 declaration at the end of the Have0State class declaration in the state.h file? It doesn't have an explicitly stated type; is it implied that it is of type Have0State??
There aren't any function pointers in your example. Also, like Marciej, I am able to compile (and run) this code.
But, since you asked, the 'have0' declaration simply declares an instance of the class. A class definition can be followed by 0 or more of these declarations (as well as initializers):
class Thing {...} one, another, many[3] = { Thing(1), Thing(2), Thing(3) };
the same as for any other type:
int counter = 0, flag = 0x80, limit = 500;
The possibility of this optional declarator list is why class, struct, union, and enum definitions must be followed with a semi-colon (to terminate the list).
But, as Karthik said, defining a variable in a header will cause "duplicate definition" errors at link time, if the header is included in more than one .cpp file. IMO it's fine though to use this technique to define and declare private objects in a .cpp file (rather than a .h file).

Inline function as a class method

I developed my own Matrix class. Constructor reads a matrix from file. Matrix has free cells and "walls". Also constructor reads start and finish points for Breadth first search (to find the shortest way from Start_point to Finish_Point).
Here is code of header:
//MyMatrix.h file
#ifndef __MYMATRIX_H__
#define __MYMATRIX_H__
#include <tchar.h>
#include <iostream>
#include <deque>
//using namespace std;
#define MAX_MATRIX_SIZE 1000
#define FREE_CELL_SIGNIFICATION '0'
#define BALL_SIGNIFICATION 'B'
#define UP_SIGNIFICATION 'U'
#define DOWN_SIGNIFICATION 'D'
#define LEFT_SIGNIFICATION 'L'
#define RIGHT_SIGNIFICATION 'R'
#define START_POINT_SIGNIFICATION 'S'
#define FINISH_POINT_SIGNIFICATION 'F'
typedef std::pair<int,int> Field_Point_Type;
//#define IS_RIGHT_NEIGHBOUR_REACHABLE(Current_Point) (((Current_Point.second+1) <= Column_Count)&&((Matrix_Field[Current_Point.first][Current_Point.second+1]==FREE_CELL_SIGNIFICATION)||(Matrix_Field[Current_Point.first][Current_Point.second+1]==FINISH_POINT_SIGNIFICATION))) ? true : false;
class Matrix {
private:
int Column_Count; //Cols
int Row_Count;//Rows
char** Matrix_Field;
Field_Point_Type Start_Point;
Field_Point_Type Finish_Point;
bool Matrix_Is_Correct;
public:
Matrix(_TCHAR* Input_File_Name);
int Breadth_first_search(unsigned int Start_X,unsigned int Start_Y,unsigned int Finish_X,unsigned int Finish_Y);
~Matrix();
inline int IS_RIGHT_NEIGHBOUR_REACHABLE(Field_Point_Type Current_Point);
};
//MyMatrix.cpp file
...
inline int Matrix::IS_RIGHT_NEIGHBOUR_REACHABLE(Field_Point_Type Current_Point)
{
return (((Current_Point.second+1) <= Column_Count)&&((Matrix_Field[Current_Point.first][Current_Point.second+1]==FREE_CELL_SIGNIFICATION)||(Matrix_Field[Current_Point.first][Current_Point.second+1]==FINISH_POINT_SIGNIFICATION))) ? true : false;
}
...
I'd like to define are the neighbour cells free for the next step of algorithm.
Of course I can use such code for this:
if (((Current_Point.second+1) <= Column_Count)&&((Matrix_Field[Current_Point.first][Current_Point.second+1]==FREE_CELL_SIGNIFICATION)||(Matrix_Field[Current_Point.first][Current_Point.second+1]==FINISH_POINT_SIGNIFICATION))) {
//Adding of right cell to deque...
...
}
but it looks ugly. I am going to add such checks for left, up and down cells.
I'd like to implement inline functions (like this: inline int IS_RIGHT_NEIGHBOUR_REACHABLE(Field_Point_Type Current_Point);).
if (IS_RIGHT_NEIGHBOUR_REACHABLE(Current_Point)) {
//Adding of right cell to deque...
...
}
It looks much better!
But I haven't use such definition of inline function before and discovered it accidentally.
Is it good programming style?
Is it better to develop simple int IS_RIGHT_NEIGHBOUR_REACHABLE(Field_Point_Type Current_Point); method within my class?
Is it better to leave such check:
if (((Current_Point.second+1) <= Column_Count)&&((Matrix_Field[Current_Point.first][Current_Point.second+1]==FREE_CELL_SIGNIFICATION)||(Matrix_Field[Current_Point.first][Current_Point.second+1]==FINISH_POINT_SIGNIFICATION))) {
//Adding of right cell to deque...
...
}
I don't think we have an established "good style" yet. Compilers capable of inlining functions from a separately compiled .cpp file are rather recent models of the most popular compilers.
Until a couple of years ago you had to have all inline functions in a .h file, so the compiler could see it while compiling the call. If your compiler is not the latest model, that might still be the rule.
inline Functions need to be implemented in header files. If it really improves your performance you need to check by benchmarks.
However good compilers might inline functions automatically (hopefully).
To your question, I would prefer to have many small functions. They are normally easier to maintain and can be checked individually if they are correct.

How can I use toString and vector between two classes in C++? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Is this possible in C++? toString(ClassName* class)
I'm trying to use toString but I have a problem in there.
I ask this question second time, because the first time I asked before had insufficient information. I just worried about the length of question. Sorry about that.
toString is in the Animal class, and Animal class has vector<Treatment> treatArray; as a data member, but the thing is I can use the data member itself, but I cannot get the data member of treatArray. These are my code:
Animal.h
#ifndef ANIMAL_H
#define ANIMAL_H
#include "jdate.h"
//#include "Treatment.h"
#include <vector>
#include <sstream>
class Treatment;
class Animal{
protected:
int id;
double weight;
int yy;
int mm;
int dd;
double dose;
double accDose;
char sex;
vector<Treatment*> treatArray;
public:
Animal();
Animal(int newid, double newweight, int yy, int mm, int dd, char newsex, vector<Treatment*> treatArray);
~Animal();
void setTreatArray(vector<Treatment*> treatArray);
vector<Treatment*> getTreatArray();
string toString();
};
Treatment.h
#ifndef TREATMENT_H
#define TREATMENT_H
#include "jdate.h"
class Treatment{
private:
int id;
jdate dayTreated;
double dose;
double accDose;
public:
Treatment(int id,jdate dayTreated, double dose);
Treatment();
~Treatment();
};
#endif
Animap.cpp
#include "Animal.h"
//using namespace std;
Animal::Animal(int newid, double newweight, int yy, int mm, int dd, char newsex, vector<Treatment*> treatArray)
{
id = newid;
weight = newweight;
yy = yy;
mm = mm;
dd = dd;
dose = 0;
accDose = 0;
sex = newsex;
}
Animal::Animal()
{
id = 0;
weight = 0;
yy = 0;
mm = 0;
dd = 0;
dose = 0;
accDose = 0;
sex = ' ';
}
void Animal::setTreatArray(vector<Treatment*> treatArray){treatArray = treatArray;}
vector<Treatment*> Animal::getTreatArray(){return treatArray;}
string Animal::toString()
{
jdate DOB(getYY(),getMM(),getDD());
ostringstream ostr;
ostr<<"Cattle / Sheep: "<<getSex()<<", Weight: "<<getWeight()
<<" kg. DOB: " <<DOB.toString()<<" Accum Dose " <<getAccDose() << "mg" << endl;
if(getTreatArray().size()==0)
ostr<<"\n No History Found\n";
else
{
for(int i=0;i<getTreatArray().size();i++)
{
//UNTIL HERE, NO ERROR FOUND, BUT ERROR OCCURS FROM THE STATEMENT BELOW
ostr<<" Treatment: " << getTreatArray().at(i)->getID() << " "
<<getTreatArray().at(i)->getDayTreated().toString()<< " "
<<getTreatArray().at(i)->getDose() <<"mg\n";
}
}
return ostr.str();
}
There are setter and getter for each class, and I cut it down.
Also, I thought it's because of initalisation of the vector, but I googled regarding initalising vector, and it says that vector is automatically initialised, so I don't have to initailise manually. Now I don't know what the problem is :(
The error message is:
1 IntelliSense: pointer to incomplete class type is not allowed l:\2011-08\c++\assignment\drug management\drug management\animal.cpp 97 30 Drug Management
You should include Treatment.h in Animal.cpp.
EDIT: To expand on the reason, the error message translates to:
"I see that you've declared a class called Treatment. But I don't see its implementation!".
So to let the compiler see its implementation where you're accessing the members of the class Treatment, you need to #include Treatment.h in your Animal.cpp. I see the reason why you don't want it to be in Animal.h, because Animal.h is being included in Treatment.h, which could cause compiler to get into a problem like:
"Okay! I'm parsing Animal.cpp...
- It includes Animal.h...
-- I'm going to expand Animal.h...
-- Animal.h includes Treatment.h...
--- I'm going to expand Treatment.h...
--- Treatment.h includes Animal.h...
---- I'm going to expand Animal.h....
---- (Loops)"
This kind of gets avoided by the #pragma once or #ifdef guards. But when them come into action, compiler goes like this:
"Okay! I'm parsing Animal.cpp...
- It includes Animal.h...
-- I'm going to expand Animal.h...
-- Animal.h includes Treatment.h...
--- I'm going to expand Treatment.h...
--- Treatment.h is using class called Animal...
--- WHERE IS THE DEFINITION FOR ANIMAL?.... ERROR!
--- (The compiler did not come to the point where class Animal was defined!)
It will also depend on whether the compiler started with Treatment.cpp or Animal.cpp. If it was Treatment.cpp, it would complain about missing definition of Treatment (just the opposite scenario of what's happened with Animal).
Now that you've declared to the compiler in Animal.h that "Keep an eye out for a class called Treatment", as long as it's not being used in Animal.h and the use of Treatment class is as a pointer, the compiler will not complain with the header file side of Animal class. But in Animal.cpp you're calling a function from Treatment class. Then the compiler goes:
Hey! You told me to look out for a class called Treatment. And now you're asking me to resolve that function definition, but I don't see the implementation of Treatment!
And hence the reason to include Treatment.h in your Animal.cpp. Animal.cpp will get compiled independently of Treatment.cpp and vice-versa and hence should not cause the clash I mentioned above.
Since you used a forward declaration in the header, you still need to include the Treatment.h file in your animal.cpp
Otherwise, the compiler still does not know what the Treatment class is.