Easier way to implement .cpp file - c++

Im just curious, but is there a way to make it so you don't have to put a class name before a function? here's an example:
HelloWorld.h
class HelloWorld{
HellowWorld();
};
HelloWorld.cpp
#include "HellowWorld.h"
HelloWorld::HelloWorld(){}
I'm wondering if there is a way to be able to have the .cpp file look like the following.
HelloWorld.cpp < New Version
#include "HellowWorld.h"
HelloWorld(){}

Functions do not have to be defined in the class, only declared.
I prefer to define the method contents in a separate file. This reduces the chance of other files compiling because I made a change to the content of a function.
Hello.hpp:
class HelloWorld
{
HelloWorld(); // Declares the constructor
};
Hello.cpp:
#include "Hello.hpp"
#include <stdio>
HelloWorld ::
HelloWorld()
{
std::cout << "Hello World\n";
}
Now I can make a change to the HelloWorld constructor and not worry about changing the header file. Because if the header file changes, all the source files that include Hello.hpp will need to be recompiled.
Edit 1: Reducing "HelloWorld::"
You can remove the HelloWorld:: part by incorporating a using statement:
#include "Hello.hpp"
#include <stdio>
using HelloWorld;
HelloWorld()
{
std::cout << "Hello Mars\n";
}

If this is a class member method then no, there is no way (apart from impractical showcase-only magic like don't put ; in .h but finish class definition in .cpp) to avoid class specification.

Related

expected type-specifier before error with unique_ptr in c++

In below code while compiling i am getting error ,
Error :
main.cpp:8:57: error: expected type-specifier before ‘Staircase’
std::unique_ptr algodiagnostic (new Staircase());
compilation command
g++ HardwareDiagnostic.cpp HardwareDiagnostic.h main.cpp -std=c++0x -o res
it works fine if compile entire code in single file without creating header file and main.cpp separately. Can anybody suggest how to fix this issue.
//HardwareDiagnostic.h//
#ifndef HARDWAREDIAGNOSTIC_H_
#define HARDWAREDIAGNOSTIC_H_
#include <iostream>
#include <memory>
using namespace std;
class HardwareDiagnostic
{
public:
virtual bool checkPort();
virtual void startDiagnostic();
virtual int publishAlgoDiagnosticInfo();
virtual void clearErrorStatus(){cout<<"Algorithm Diagnostics"<<endl;}
virtual ~HardwareDiagnostic() {cout<<"calling virtual destructor"<<endl;}
};
#endif /* HARDWAREDIAGNOSTIC_H_ */
//HardwareDiagnostic.cpp//
#include"HardwareDiagnostic.h"
class Localization : public HardwareDiagnostic
{
public:
Localization() { cout << "calling Localization constructor";}
bool checkPort(){cout<<"checkport :Localization";}
void startDiagnostic(){cout<<"start Diagnostic:Localization";}
int publishAlgoDiagnosticInfo() {cout<<"publish Diagnostic:Localization";}
void clearErrorStatus(){ cout<<"Localization:publish Diagnostic";}
~Localization () { cout<<"calling Localization destructor ";}
};
class Staircase : public HardwareDiagnostic
{
public:
Staircase () {cout<<"Staircase constructor";}
bool checkPort(){cout<<"Staircase";}
void startDiagnostic(){cout<<"StairCase:start Diagnostic";}
int publishAlgoDiagnosticInfo() {cout<<"StairCase:publish Diagnostic";}
void clearErrorStatus(){ cout<<"staircase:publish Diagnostic";}
~Staircase(){cout<<"calling Staircase destructor";}
};
//main.cpp//
#include "HardwareDiagnostic.h"
using namespace std;
int main() {
std::unique_ptr<HardwareDiagnostic> algodiagnostic (new Staircase());
return 0;
}
When compiler works on main.cpp, it sees Staricase usage, but doesn't see declaration for Staircase class, so error is raised. Your main.cpp file includes header, which describes HardwareDiagnostic class only, but no info for Staircase is provided.
Good practice is to keep class declarations in header files, rather than cpp files, so any other source can include header file and start using described class. It's OK to include definition for trivial class methods in header file as well (like getters/setters), but complicated methods should be declared in header file and defined in coresponding cpp file.
In your case I would do the following:
HardwareDiagnostic.h describes HardwareDiagnostic class. There is no using std line in this file, so anyone including this file won't implicitly start using undesired namespace. All methods are declared, but not defined.
HardwareDiagnostic.cpp defines methods of HardwareDiagnostic class. So there is using std line and definition of all methods.
Localization.h includes HardwareDiagnostic.h and describes Localization class. Having separate file for each class becomes very convenient as project grows.
Localization.cpp defines methods of Localization class.
Staircase.h and Staircase.cpp are built the same way as localization.
main.cpp includes HardwareDiagnostic.h and Staircase.h

how to write into a single file (create from stream class) from two different files using ofstream

I am using ofstream to write into a file.
ofstream myfile;
myfile.open("test.txt",ios::app);
Now, I want this variable "myfile" to be used by two different files.
eg:example.cc and example1.cc
I have declared 'myfile' in example.cc file, and after a function call when the call goes to example1.cc, I am using the same name 'myfile ' to write into the same file test.txt.
But I am getting error as
#example1.cc 'myfile' was not declared in the scope
I know that its not in scope, But as I am new to cpp , I don't know how to make a same file available to two different file.
If I declare a file in example1.cc than it will become a new file rite?
I think that I have finally understood what you are trying to achieve. You want to have access to one stream from two different source files(translation units). I assume that due to the fact that you are new to C++, I should suggest the simplest solution. Please do not assume that it is the best one, as it has a lot of caveats. We have project that contains three source files: foo1.cpp, foo2.cpp, main.cpp:
File foo1.cpp
#include <fstream>
extern std::ofstream logger;
void foo1()
{
logger << "Foo1 started" << std::endl;
//some stuff
logger << "Foo1 finished" << std::endl;
}
File foo2.cpp
#include <fstream>
extern std::ofstream logger;
void foo2()
{
logger << "Foo2 started" << std::endl;
//some stuff
logger << "Foo2 finished" << std::endl;
}
File main.cpp
#include <fstream>
#include <iostream>
std::ofstream logger;
void foo1();
void foo2();
int main()
{
logger.open("./data.txt", std::ios::app);
foo1();
foo2();
logger.close();
}
This code would hope fully compile and after execution there will be a file data.txt with this content:
Foo1 started
Foo1 finished
Foo2 started
Foo2 finished
I think that the most interesting for you should be the fourth line from main.cpp and third lines in foo1.cpp and foo2.cpp.
The fourth line in main.cpp, because the logger is declared outside main function, this allows other function to reach the logger and use it. This is true not only for the functions in this .cpp file. The compiler will put the address to this variable in symbol table for .o file, and this is exactly what was my intention. You may try to add static keyword before it and see what will happen. (it will disable this behavior)
Third lines from foo1.cpp and foo2.cpp informs the compiler that there will be such a variable(it will now now its name and type) in the symbol table of some .o(main.o in our case). The compiler will generate the code that uses such a variable and will place in the symbol table that this file need such variable to be provided(aka. undefined symbol).
If you manage to understand this you may also use your own header file. There is some kind of duplication in this "project". The first three lines of foo1.cpp and foo2.cpp are exactly the same. You may want to use header file to reduce this.
logger.hpp:
#include <fstream>
extern std::ofstream logger;
foo1.cpp:
#include "logger.hpp"
void foo1()
{
...
foo2.cpp
#include "logger.hpp"
void foo2()
{
...
The headers files are usually used just for this, to keep the interface to other source files in one place, additionally to in-line function and templates. If you will ever think to use it for something else, please think again

How to access non member functions that are in a seperate file (.cpp) than main

So I am working on my first multiple file, non-toy, c++ project. I have a class that represents a multi-spectral image and all the information that goes along with it.
My problem is how to design the part of the program that loads and object of this class with a file from disk!
I don't think I need a class for this. Would switching to a functional approach be better for the file loading. This way I can have just a source file (.cpp) that has functions I can call while passing in pointers to the relevant objects that will be updated by the file accessed by the function.
I don't think static functions are what I want to use? As I understand it they(static functions) are for accessing static variables within a class, aren't they?
If I go the functional route, from main(), how do I access these functions? I assume I would include the functions .cpp file at the beginning of the main() containing file. From there how do I call the functions. Do i just use the function name or do I have to pre-pend something similar to what you have to pre-pend when including a class and then calling its methods.
Here is some example code of what I have tried and the errors I get.
OpenMultiSpec.cpp
#include <iostream>
void test(){
std::cout << "Test function accessed successfully" << std::endl;
}
main.cpp
int main(){
test();
return 1;
}
The error says " 'test' was not declared in this scope "
OpenMultiSpec.h
void test();
main.cpp
#include "OpenMultiSpec.h"
int main(){
test();
return 1;
}
If they're in two separate files, and in your case, one being a header, use
#include "OpenMultiSpec.h"
If you decide to only use one file (as your comment says above), you won't need #include for your header file. Just place your function declaration anywhere before you call it.
#include <iostream>
void test() {
std::cout << "Test function accessed successfully" << std::endl;
}
int main() {
test();
return 1;
}

Classes included within main() method

If I have some code like
main(int argc, char *argv[])
{
...
#include "Class1.H"
#include "Class2.H"
...
}
Generally the main() method is the starting point of every application and the content within main() is to be executed. Am I right in the assumption that the content of all classes included into main() will be executed when main() is started?
greetings
Streight
No, no, NO.
First of all, you don't #include a file within a function. You #include a file at the beginning of a file, before other declarations. OK, you can use #include anywhere, but you really just shouldn't.
Second, #include doesn't execute anything. It's basically just a copy-paste operation. The contents of the #included file are (effectively) inserted exactly where you put the #include.
Third, if you're going to learn to program in C++, please consider picking up one of our recommended texts.
You commented:
I am working with the multiphaseEulerFoam Solver in OpenFoam and
inside the main() of multiphaseEulerFoam.C are classes included. I
assume that the classes have the right structure to be called in
main()
That may be the case, and I don't doubt that the classes have the right structure to be called from main. The problem is main will be malformed after the #includes because you'll have local class definitions and who knows what else within main.
Consider this. If you have a header:
foo.h
#ifndef FOO_H
#define FOO_H
class Foo
{
public:
Foo (const std::string& val)
:
mVal (val)
{
}
private:
std::string mVal;
};
#endif
And you try to include this in main:
main.cpp
int main()
{
#include "foo.h"
}
After preprocessing the #include directive, the resulting file that the compiler will try to compile will look like this:
preprocessed main.cpp
int main()
{
#ifndef FOO_H
#define FOO_H
class Foo
{
public:
Foo (const std::string& val)
:
mVal (val)
{
}
private:
std::string mVal;
};
#endif
}
This is all kinds of wrong. One, you can't declare local classes like this. Two, Foo won't be "executed", as you seem to assume.
main.cpp should look like this instead:
#include "foo.h"
int main()
{
}
#define and #include are just textual operations that take place during the 'preprocessing' phase of compilation, which is technically an optional phase. So you can mix and match them in all sorts of ways and as long as your preprocessor syntax is correct it will work.
However if you do redefine macros with #undef your code will be hard to follow because the same text could have different meanings in different places in the code.
For custom types typedef is much preferred where possible because you can still benefit from the type checking mechanism of the compiler and it is less error-prone because it is much less likely than #define macros to have unexpected side-effects on surrounding code.
Jim Blacklers Answer # #include inside the main () function
Try to avoid code like this. #include directive inserts contents of the file in its place.
You can simulate the result of your code by copy-pasting file content from Class1.H and Class2.H inside the main function.
Includes do not belong into any function or class method body, this is not a good idea to do.
No code will be executed unless you instantiate one of your classes in your header files.
Code is executed when:
Class is instantiated, then it's constructor method is called and the code inside the method is executed.
If there are variables of a class type inside your instantiated class, they will too run their constructors.
When you call a class method.
Try this example:
#include <iostream>
using namespace std;
int main()
{
class A
{ public:
A() { cout << "A constructor called" << endl; }
};
// A has no instances
class B
{ public:
B() { cout << "B constructor called" << endl; }
void test() { cout << "B test called" << endl; }
} bbb;
// bbb will be new class instance of B
bbb.test(); // example call of test method of bbb instance
B ccc; // another class instance of B
ccc.test(); // another call, this time of ccc instance
}
When you run it, you'll observe that:
there will be no instance of class A created. Nothing will be run from class A.
if you intantiate bbb and ccc, their constructors will be run. To run any other code you must first make a method, for example test and then call it.
This is an openFoam syntax he is correct in saying that open Foam treats #include like calling a function. In OpenFoam using #include Foo.H would run through the code not the class declaration that is done in a different hierarchy level. I would recommend all openFoam related question not be asked in a C++ forum because there is so much stuff built onto C++ in openFoam a lot the rules need to be broken to produce a working code.
You're only including declarations of classes. To execute their code, you need to create class instances (objects).
Also, you shouldn't write #include inside a function or a class method. More often than not it won't compile.

Defining a class method in another file

I know how to define a class method inside of the same file with which the class is in.
For example:
class Robot
{public:
int location;
void Moves(); //Class method to be defined
}
void Robot::Moves()
{//Method definition here }
I do NOT know hot to define a class outside of the file in which the class is in. I tried creating a .hpp file and defining a class method inside of it, but my compiler signified that it could not load a class definition from a file other than the one the class was created in, or it would be as though I was placing a function's definition before the include directives.
Please note: The original class file is also in a .hpp file, as I have yet to learn how to use .cpp files other than the main one.
This is done using C++/Win32.
Create a .cpp file along these guidelines
Include your class header file in your .cpp file
Include all necessary headers you would use in main.cpp
use the scope operator for your class
#include <iostream>
#include "foo.hpp"
foo::foo()
{
// code here
}
void foo::OtherFunc()
{
// other stuff here
}
Just put your definition in a .cpp file and link it with your application.
Robot.hpp:
class Robot
{public:
int location;
void Moves(); //Class method to be defined
}
Robot.cpp:
#include "Robot.hpp"
void Robot::Moves()
{//Method definition here }