Inline function as a class method - c++

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.

Related

Is it bad to use #include in the middle of code?

I keep reading that it's bad to do so, but I don't feel those answers fully answer my specific question.
It seems like it could be really useful in some cases. I want to do something like the following:
class Example {
private:
int val;
public:
void my_function() {
#if defined (__AVX2__)
#include <function_internal_code_using_avx2.h>
#else
#include <function_internal_code_without_avx2.h>
#endif
}
};
If using #include in the middle of code is bad in this example, what would be a good practice approach for to achieve what I'm trying to do? That is, I'm trying to differentiate a member function implementation in cases where avx2 is and isn't available to be compiled.
No it is not intrinsically bad. #include was meant to allow include anywhere. It's just that it's uncommon to use it like this, and this goes against the principle of least astonishment.
The good practices that were developed around includes are all based on the assumption of an inclusion at the start of a compilation unit and in principle outside any namespace.
This is certainly why the C++ core guidelines recommend not to do it, being understood that they have normal reusable headers in mind:
SF.4: Include .h files before other declarations in a file
Reason
Minimize context dependencies and increase readability.
Additional remarks: How to solve your underlying problem
Not sure about the full context. But first of all, I wouldn't put the function body in the class definition. This would better encapsulate the implementation specific details for the class consumers, which should not need to know.
Then you could use conditional compilation in the body, or much better opt for some policy based design, using templates to configure the classes to be used at compile time.
I agree with what #Christophe said. In your case I would write the following code
Write a header commonInterface.h
#pragma once
#if defined (__AVX2__)
void commonInterface (...) {
#include <function_internal_code_using_avx2.h>
}
#else
void commonInterface (...) {
#include <function_internal_code_without_avx2.h>
}
#endif
so you hide the #if defined in the header and still have good readable code in the implementation file.
#include <commonInterface>
class Example {
private:
int val;
public:
void my_function() {
commonInterface(...);
}
};
#ifdef __AVX2__
# include <my_function_avx2.h>
#else
# include <my_function.h>
#endif
class Example {
int val;
public:
void my_function() {
# ifdef __AVX2__
my_function_avx2(this);
# else
my_function(this);
# endif
}
};
Whether it is good or bad really depends on the context.
The technique is often used if you have to write a great amount of boilerplate code. For example, the clang compiler uses it all over the place to match/make use of all possible types, identifiers, tokens, and so on. Here is an example, and here another one.
If you want to define a function differently depending on certain compile-time known parameters, it's seen cleaner to put the definitions where they belong to be.
You should not split up a definition of foo into two seperate files and choose the right one at compile time, as it increases the overhead for the programmer (which is often not just you) to understand your code.
Consider the following snippet which is, at least in my opinion, much more expressive:
// platform.hpp
constexpr static bool use_avx2 = #if defined (__AVX2__)
true;
#else
false;
#endif
// example.hpp
class Example {
private:
int val;
public:
void my_function() {
if constexpr(use_avx2) {
// code of "functional_internal_code_using_avx2.h"
}
else {
// code of "functional_internal_code_without_avx2.h"
}
};
The code can be improved further by generalizing more, adding layers of abstractions that "just define the algorithm" instead of both the algorithm and platform-specific weirdness.
Another important argument against your solution is the fact that both functional_internal_code_using_avx2.h and functional_internal_code_without_avx2.h require special attention:
They do not build without example.h and it is not obvious without opening any of the files that they require it. So, specific flags/treatment when building the project have to be added, which is difficult to maintain as soon as you use more than one such functional_internal_code-files.
I am not sure what you the bigger picture is in your case, so whatever follows should be taken with a grain of salt.
Anyway: #include COULD happen anywhere in the code, BUT you could think of it as a way of separating code / avoiding redundancy. For definitions, this is already well covered by other means. For declarations, it is the standard approach.
Now, this #includes are placed at the beginning as a courtesy to the reader who can catch up more quickly on what to expect in the code to follow, even for #ifdef guarded code.
In your case, it looks like you want a different implementation of the same functionality. The to-go approach in this case would be to link a different portion of code (containing a different implementation), rather than importing a different declaration.
Instead, if you want to really have a different signature based on your #ifdef then I would not see a more effective way than having #ifdef in the middle of the code. BUT, I would not consider this a good design choice!
I define this as bad coding for me. It makes code hard to read.
My approach would be to create a base class as an abstract interface and create specialized implementations and then create the needed class.
E.g.:
class base_functions_t
{
public:
virtual void function1() = 0;
}
class base_functions_avx2_t : public base_functions_t
{
public:
virtual void function1()
{
// code here
}
}
class base_functions_sse2_t : public base_functions_t
{
public:
virtual void function1()
{
// code here
}
}
Then you can have a pointer to your base_functions_t and instanciate different versions. E.g.:
base_functions_t *func;
if (avx2)
{
func = new base_functions_avx2_t();
}
else
{
func = new base_functions_sse2_t();
}
func->function1();
As a general rule I would say that it's best to put headers that define interfaces first in your implementation files.
There are of course also headers that don't define any interfaces. I'm thinking mainly of headers that use macro hackery and are intended to be included one or more times. This type of header typically doesn't have include guards. An example would be <cassert>. This allows you to write code something like this
#define NDEBUG 1
#include <cassert>
void foo() {
// do some stuff
assert(some_condition);
}
#undef NDEBUG
#include <cassert>
void bar() {
assert(another_condition);
}
If you only include <cassert> at the start of your file you will have no granularity for asserts in your implementation file other than all on or all off. See here for more discussion on this technique.
If you do go down the path of using conditional inclusion as per your example then I would strongly recommend that you use an editor like Eclipse or Netbeans that can do inline preprocessor expansion and visualization. Otherwise the loss of locality that inclusion brings can severely hurt readability.

Using header files to make an ADT: declaration of ‘int Queue::size()’ outside of class is not definition [-fpermissive]

I've combed through Google and Stack Overflow looking for an answer to this problem. I know this is super basic, and I'm really irritated I can't figure out what is wrong. So my graduate professor wants us to make an implementation of a Queue for integers. Why? Because this is "Principles of Programming" and we're basically going over ever single little detail with super concise definitions. It's honestly the biggest waste of a three hour class I've ever had to take, but at least the teacher is good. Anyways, I've got the class definition in a .h file, which contains
#ifndef QUEUE_H
#define QUEUE_H
class Queue
{
private:
std::vector<int> myQueue;
public:
int push(int);
int pop_front();
int size();
bool empty();
};
#endif
So, I feel like Queue::size() and Queue::empty are declared right? Well, in my queue.cpp file, I've got the details of these functions...
#include <vector>
#include "queue.h"
int Queue::push(int intToPush)
{
myQueue.push_back(intToPush);
return 0;
};
int Queue::pop_front()
{
int front = myQueue.front();
myQueue.erase(myQueue.begin());
return front;
};
/*
int Queue::size(); <- It was these semicolons
{
return myQueue.size();
};
bool Queue::empty(); <- This one too.
{
return myQueue.empty();
};*/
And when I compile it like this, it does fine, but when I include those two that I have commented out, it gives the error I put in the title of this post.
I'm really sorry that this is so basic and stupid, but I can't find anything to help me and it really perplexes me that these functions are causing the compiler to say that their being declared outside of the class. I tried using the generic returns, 0 and false, and get the same compilation error.
Remove the semicolon from the end of the function names in the cpp file and try compiling again. You can also remove the semicolons trailing the terminating brackets of all of the function definitions. They are not necessary.

Doxygen and multiple #defines with the same name

This is a small experiment I tried out with Doxygen.
Say I have 6 files:
h1.h:
class A
{
public:
int func1();
}
f1Data.h:
#define val 10
f1.cpp:
#include "h1.h"
#include "f1Data.h"
int A::func1()
{
return val;
}
h2.h:
#include "h1.h"
class B: public A
{
public:
int func2();
};
f2Data.h
#define val 20
f2.cpp
#include "h2.h"
#include "f2Data.h"
int B::func2()
{
return val;
}
When I put GENERATE_XML=yes and CALL_GRAPH=yes in my configuration file and run doxygen, I see a bug in the generated XML file. In particular, I see that among the references of A::func1() the #defined value from f2Data.h is given instead of the #defined value from f1Data.h. This happens only when the name of the macro is same in both the files[In this case, val].
Can anyone tell me if this is a bug with doxygen or incorrect usage of doxygen on my part?
Doxygen makes a couple of assumptions while processing the code:
The headers are properly guarded (so they need to be processed only once).
Public symbol names are unique within a single project.
These are generally good programming practices, but not enforced by C as your example demonstrates.
If you do not adhering two the above rules, the output of doxygen can be incorrect.

How can I be getting "already defined" linker errors here?

I'm making my first attempt at unit testing in C++, and I haven't used C++ in a number of years (I'm mainly a C# coder at the moment). It seems like I'm making a right pig's ear of it - I hope someone can steer me back onto the righteous path. I'm just getting started here and would really like to be implementing these tests using the best practice possible, so any and all comments are welcome, even though I'm most concerned with my linker error at present.
So, I have an overall solution "Technorabble", with sub-projects "CalibrationTool" and "CalibrationToolUnitTests".
CalibrationTool has a MathUtils.h file:
#ifndef __math_utils__
#define __math_utils__
#include "stdafx.h"
#include <vector>
namespace Technorabble
{
namespace CalibrationTool
{
double GetDoubleVectorAverage(std::vector<double> v)
{
double cumulativeValue = 0;
for(std::vector<double>::iterator iter = v.begin(); iter != v.end(); ++iter)
{
cumulativeValue += *iter;
}
return cumulativeValue / v.size();
}
}; // end namespace CalibrationTool
}; // end namespace Technorabble
#endif // !__math_utils__
(But no .cpp file as I was having all kinds of (somewhat similar) issues getting my template function working - so I ended up defining that inline).
Moving on to the Unit Tests project, I have a main.cpp:
#include "MathUtilsTest.h"
void RunMathUtilsTests();
int main()
{
RunMathUtilsTests();
// Other class tests will go here when I have things to test
}
void RunMathUtilsTests()
{
MathUtilsTest* mathUtilsTest = new MathUtilsTest();
mathUtilsTest->RunTests();
delete mathUtilsTest;
}
Finally, the header and cpp for the MathUtilsTest class, again, fairly simple:
.h:
#ifndef __MATH_UTILS_TEST__
#define __MATH_UTILS_TEST__
#include "CalibrationToolUnitTestsLogging.h"
#include "..\CalibrationTool\MathUtils.h"
class MathUtilsTest
{
public:
MathUtilsTest();
~MathUtilsTest();
bool RunTests();
private:
bool GetDoubleVectorAverageTest();
}; // end class MathUtilsTest
#endif
.cpp:
#include "MathUtilsTest.h"
#include <sstream>
bool MathUtilsTest::RunTests()
{
return GetDoubleVectorAverageTest();
}
MathUtilsTest::~MathUtilsTest()
{
}
MathUtilsTest::MathUtilsTest()
{
}
bool MathUtilsTest::GetDoubleVectorAverageTest()
{
bool passed = true;
std::vector<double> values;
for (int i = 1; i < 23; i++)
{
values.push_back(i);
}
// vector becomes: 1, 2, 3, 4, .....20, 21, 22. Average is 11.5
double expectedAverage = 11.5;
double calculatedAverage = Technorabble::CalibrationTool::GetDoubleVectorAverage(values);
if (calculatedAverage != expectedAverage)
{
std::ostringstream s;
s << calculatedAverage;
std::string avgString = s.str();
CalibrationToolUnitTestsLogging::Write("Failed MathUtilsTest.GetDoubleVectorAverageTest: " + avgString);
passed = false;
}
else
{
CalibrationToolUnitTestsLogging::Write("Passed MathUtilsTest.GetDoubleVectorAverageTest");
}
return passed;
}
This all seemed fine to me, I'm protecting my header with #ifndef, etc. But I'm still getting the following errors:
1) error LNK1169: one or more multiply defined symbols found
2) error LNK2005: "double __cdecl Technorabble::CalibrationTool::GetDoubleVectorAverage(class std::vector >)" (?GetDoubleVectorAverage#CalibrationTool#Technorabble##YANV?$vector#NV?$allocator#N#std###std###Z) already defined in main.obj C:_SVN\Technorabble\Windows Software\CalibrationToolUnitTests\MathUtilsTest.obj
How can this be? Can anyone spot where it's going wrong?
Functions defined in headers should be marked as inline:
inline double GetDoubleVectorAverage(std::vector<double> v)
{
}
If it's longer than a couple of lines, consider moving it to an implementation file.
pragmas or include guards don't protect against multiple definitions.
Note that you should pass v by const reference rather than by-value.
You are defining a function GetDoubleVectorAverage in a header. This means that it will be defined in every translation unit (i.e. every source file) that includes that header. If your program contains more than one such translation unit, then you'll have more than one definition - which isn't allowed.
Solutions are:
Add inline to the function definition, to relax this rule and allow multiple identical definitions; or
Move the function definition into a source file, and only declare it in the header.
I'm protecting my header with #ifndef
That only prevents the header from being included more than once within the same translation unit. It doesn't prevent inclusion from more than one unit.
Also, you shouldn't use a reserved name like __math_utils__ as a header guard, even if the internet is littered with examples of dodgy code doing that.
I was having all kinds of (somewhat similar) issues getting my template function working
Templates usually need to be defined in header files, to make the definition available at the point of use. Function templates are implicitly inline, but normal functions (like this one) aren't.

c++, MCVS 2012, header file, vector and namespaces [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have a trouble with finding answer for my questions (Q), so I registered here to ask you guys how it really works (or don't works) ;)
I am writing in c++, in Visual Studio 2012, but still don't really know how it is with #includes, namespaces etc. in header files. Do I even need to use them?
(Q1): Let's say I have one .cpp file and few .h files, which are using, for example: vectors, things from <algorithm>, <ctime> and some other libraries, but I do not write #include <something> in header files, only in .cpp. Is it correct? Or should I include everything I use in every header?
Usually everything works for me, I can even say it always "works", because I don't have too much experience yet and I was usually containing everything in one .cpp and 1 or 2 headers with some void functions. But don't know if it works because it should, or because, for example, mu compiler allows that and in some issues it can cause errors.
(Q2): Now a thing about using namespace std;
In some cases functions in .h files works without it, but sometimes not. For example, the voids that are working (just simple voids for merge-sort):
#ifndef LISTA_1_H
#define LISTA_1_H
#include "Lista_0_Zadanie_1.h"
void MERGE(vector<double> &A, int p, int q, int r)
{
int i = p;
int j = q+1;
int lenght = r - p + 1;
int k=0;
vector<double> merged;
merged.assign (lenght,0);
while((i<=q)&&(j<=r))
{
if(A[i] <= A[j])
{
merged[k]=A[i];
++i;
}
else
{
merged[k]=A[j];
++j;
}
k++;
}
if(j<=r)
{
while(j<=r)
{
merged[k]=A[j];
++j;
++k;
}
}
if(i<=q)
{
while(i<=q)
{
merged[k]=A[i];
++i;
++k;
}
}
for (i=0;i<lenght;++i)
A[p+i]=merged[i];
}
void MERGESORT(vector<double> &A, int k, int l)
{
if(k<l)
{
int m = (k+l)/2;
//int mp = m+1;
// cout << "koza"<<endl;
MERGESORT(A,k,m);
MERGESORT(A,m+1,l);
MERGE(A,k,m,l);
}
}
void TRIPLE_MERGESORT(vector<double> &A, int k, int l)
{
if(k<l)
{
int one_third = (l-k)/3;
int two_third = 2*(l-k)/3; // k < k+one_third < k+two_third < l
TRIPLE_MERGESORT(A,k,k+one_third);
TRIPLE_MERGESORT(A,k+one_third+1,k+two_third);
TRIPLE_MERGESORT(A,k+two_third+1,l);
MERGE(A,k,k+one_third,k+two_third);
MERGE(A,k,k+two_third,l);
}
}
void INSERT_MERGESORT (vector<double> &A, int k, int l)
{
if(l<19) // l=n-1, więc n<20 <=> l < 19
{
double y;
int i,j;
for(i=0; i<l+1; ++i)
{
y = A[i];
j = i-1;
while((j>=0) && (A[j]>y) )
{
A[j+1] = A[j];
--j;
}
A[j+1]=y;
}
}
else
MERGESORT(A,k,l);
}
#endif
... and in some cases it does not work, if I do not write "using namespace std;" or add " std:: " in correct place (here before vectors), it does not work:
#ifndef SCHEMAT_HORNERA_H
#define SCHEMAT_HORNERA_H
//using namespace std;
void HORNER( int n, double z0, double p_z0, vector<double> a, vector<double> &B)
{
B[n] = a[n];
for(int k = n-1; k>=0; --k)
{
B[k] = a[k] + z0*B[k+1];
}
}
#endif
So here's my question: Should I always use "std::" or "using namespace std"?
If yes, why are my files until now "working"? Because in some cases VS allows for that, while it is not correct and some compilers and not allow for this?
Q1) Whether or not you need to #include a header with a full definition depends on if you need a full definition, or if just a forward-declare will do. In the case of needing just a forward-declaration, all you need to tell the compiler is the name of something. An example is if you need a pointer-to-something:
// fw-decl Foo
class Foo;
// define Gizmo
class Gizmo
{
public:
void DoIt();
Foo* mFoo; // just need a pointer, so don't need a full definition of foo
};
Later you will need a full definition if you actually use the Foo object, as with:
#include "foo.h"
#include "gizmo.h"
void Foo::DoIt()
{
mFoo->DoSomething(); // now we need a full definition
}
On the other hand, if the compiler needs to know for example how big Foo is, then you need a full definition.
#include "foo.h"
class Gizmo
{
public:
Foo mFoo; // need a full definition here
};
As a general rule of thumb, it is best to provide full definitions only when necesarry, so as to keep compilation times as quick as possible.
Q2) Simplified rule-of-thumb: never using namespace std. If you simply follow this rule of thumb without ever thinking about it, you will never have problems with namespace collisions, polluting the global namespace, or other nastiness.
Of course, this rule of thumb is a little over-simplified for those who actually think for a living, so here's a slightly better one:
1) Never using namespace in a header
2) Never using namespace in a source file unless it's your own namespace you're implementing.
Rules of thumb can be overly restrictive, and this is no exception, but it will get you on your way without venturing too far in to a landmine. The problem with using anmespace is it brings whatever is in that namespace in to global scope. Suppose you have your own header file:
mystring.h
namespace MyString
{
class string
{
// ...
};
}
...and then in the source file:
#include "mystring.h"
#include <string>
using namespace MyString;
using namespace std;
string s; // OOPS: which "string" is this? MyString::string, or std::string?
This ambiguity is obvious here, but int he real world it can be much less obvious, and result in some very hard-to-detect bugs.
(Q1) It is important to remember what an include declaration actually does. Basically it is nothing more than a simple copy/paste of the entire file which is being included in the new file.
Since header files are included in many places, it is generally frowned upon to have many unnecessary includes in .h files (unless using templates). In general, do not include in a header file when a forward declaration will suffice.
In the .cpp file, include ALL files necessary so that the program can compile.
Because you are using visual studio, you must be careful because it is very lenient on including files from the standard library that you actually forgot to include, and you may experience problems compiling on other systems.
(Q2) In a header file you should not have a "using" statement. Remember that the include statement is a simple copy/paste; so for that reason if you have a using statement it will be included in the new file as well.
In .h files you should always use std::vector, std::set, etc.
In .cpp files, it is ok to have using namespace std, using std::vector, etc.
(Sidebar) Related to your code, you should split it up into header files and cpp files. Do not have the definition in the .h file, only the declaration. Make a .cpp file and define the algorithm in there. Also do not have define guards in a .cpp file. Never include a .cpp file!