I have the following code in a single cpp file (tested.cpp):
class tested {
private:
int x;
public:
tested(int x_inp) {
x = x_inp;
}
int getValue() {
return x;
}
};
Now I want to write a header file for this code. How should it look? And what should I change in my cpp file after I have a header file. I supposed that my header file should be something like that:
class tested {
private:
int x;
public:
tested(int x);
int getValue();
}
Then in my cpp file I should #include "tested.h". I also need to replace the whole class by:
tested::tested(int c_inp) {
x = x_inp;
}
tested::getValue(){
return x;
}
Is it right?
To make your header file more universal, you could use the macro #ifndef like it is done here
http://www.fredosaurus.com/notes-cpp/preprocessor/ifdef.html
You also need to type the type of return for methods other than constructor and destructor :
int tested::getValue(){
return x;
}
Yep, as freude said before, it is usual to protect header files against multiple inclusions with #ifndef (especially in big projects, or if your file may be part of one).
Some other things (essentially matter of style):
It isn't mandatory to put "private:" for the first members of the class, since all class members are private by default.
It is usual to put a character before (or after) the name of each attribute of the class (e.g. "x_" instead of "x")
Related
I'm aware of using function prototypes, and I was under the impression that forward class declarations could serve a similar purpose when main() and a class are in the same file. For example, I would have expected this would compile:
// main.cpp
#include <iostream>
// class prototypes
class MyClass;
int main(void)
{
MyClass myClass;
// do stuff with myClass here
return(0);
}
class MyClass
{
public:
int someInt;
double someDouble;
// more stuff here . . .
};
But on the MyClass myClass; line I'm getting the error 'myClass' uses undefined class 'MyClass'. What am I doing wrong?
P.S. I'm aware that I could cut/paste main() below all the classes it uses and that would fix the error, but I'd prefer to keep main() as the first function or class.
P.P.S. I'm aware that in any substantial size production program main(), .h content, and .cpp content would be in 3 separate files. In this case I'm attempting to write a small example or test program where main and a class(es) are in the same file.
Forward declarations can only be used via pointers or references.
Calling a constructor function doesn't fall into this category.
I'm aware that I could cut/paste main() below all the classes it uses and that would fix the error, but I'd prefer to keep main() as the first function or class.
That's why usually header files are used, instead of placing all the declarations and definitions in the main.cpp file.
I'm aware that in any substantial size production program main(), .h content, and .cpp content would be in 3 separate files. In this case I'm attempting to write a small example or test program where main and a class(es) are in the same file.
You should still stick to that idiom though, everything else would probably end up in a mess.
This doesn't use forward declarations but it partially addresses the spirit of a single main.cpp with your "main" at the top. I find this technique sometimes useful when you want to share something via an online C++ ide where a single file is much easier to deal with, and you want to focus on the action in main rather than implementation detail in helper structs/classes etc.
#include <iostream>
template<typename MyClass,typename MyOtherClass>
int main_()
{
MyClass a;
a.do_foo();
MyOtherClass b;
b.do_bar();
return 0;
}
struct MyClass
{
void do_foo() { std::cout << "MyClass: do_foo called\n"; }
};
struct MyOtherClass
{
void do_bar() { std::cout << "MyOtherClass: do_bar called\n"; }
};
int main()
{
return main_<MyClass,MyOtherClass>();
}
In one of my classes header file Lfo.h, I have a class definition where I put the member function definition out of the class (It might be better to have a separate .cpp file but it should be ok put here?):
// Lfo.h
class CLfo
{
public:
static int create (CLfo*& pCLfo);
};
int CLfo::create(CLfo *&pCLfo)
{
pCLfo = new CLfo;
return 0;
}
Then I have another class called CVibrato:
// Vibrato.h
class CVibrato
{
public:
static int create (CVibrato*& pCVibrato);
private:
CVibrato();
};
and the .cpp file (in the cpp file, I include Lfo.h because later on the vibrato class will have a lfo member but I haven't implemented right now):
// Vibrato.cpp
#include "Lfo.h"
#include "Vibrato.h"
int CVibrato::create(CVibrato *&pCVibrato)
{
pCVibrato = new CVibrato();
return 0;
}
CVibrato::CVibrato()
{
}
Then I want to create a instance of vibrato class in main()
#include "Vibrato.h"
#include "Lfo.h" // if comment this line out there will be no error, why is that?
int main()
{
CVibrato *vibrato = 0;
CVibrato::create(vibrato);
return 0;
}
However I get a 1 duplicate symbol for architecture x86_64 error. What is duplicated? It seems the reason is in Lfo.h, I put the definition of the member function outside of the class, if I put it inside, the program runs properly. But I cannot understand. In c++, aren't we allowed to do this? By the way, if one of my class (in my case vibrato) is going to have a class member of another class (in this case lfo), should I include the header file of member class in .h (vibrato.h) file or .cpp (vibrato.cpp) file?
Classes are declarations. No code is produced from a declaration. Even if you have a member function in the class, it is treated as if an inline by the compiler. Function bodies can be put in a header but should always be declared as inline. The compiler may not actually inline it, but it will treat it as a single instance for code creation.
Any time you:
void function( ) { }
Code is created for that function. If a header is included more than once the compiler is told to create the code more than once. But all functions must have unique names! So you get the duplicate error. That is why code generating lines belong in the .cpp files.
'inline' tells the compiler not to create immediate code but to create the code at the usage point.
You can't put class method definition directly in a header file, unless you explicitly mark it as inline. Like the following:
// Lfo.h
class CLfo
{
public:
inline static int create (CLfo*& pCLfo);
};
int CLfo::create(CLfo *&pCLfo)
{
pCLfo = new CLfo;
return 0;
}
Or,
// Lfo.h
class CLfo
{
public:
static int create (CLfo*& pCLfo);
};
inline int CLfo::create(CLfo *&pCLfo)
{
pCLfo = new CLfo;
return 0;
}
In java there is no header file. We import Class and use function. We can also extend them. In C++ there is header file. We include them and use function. Now my question, how to inherit them like java extends and is it possible?
Every program has its own way of doing something. In c++ you can do like:
//filename foo1.h
class foo1
{
}
Now inn another file say foo2.h
//filename foo2.h
#include "foo1.h"
class foo2 : public foo1
{
}
Java combines two things which C++ separates: the class definition and the definition of its members.
Java:
class Example {
private String s;
protected static int i = 1;
public void f() {
System.out.println("...");
}
public Example() {
s = "test";
}
}
C++ class definition:
class Example
{
private:
std::string s;
protected:
static int i;
public:
void f();
Example();
};
C++ definition of members:
int Example::i = 1;
void Example::f()
{
std::cout << "...\n";
}
Example::Example() :
s("test")
{
}
The separation into *.h and *.cpp files is purely conventional. It typically makes sense to put the class definition into the *.h file and the definition of the members into the *.cpp file. The reason why it makes sense is that some other code using the class only needs the class definition, not the definition of its members. That "other code" includes subclasses. By providing the class definition in a separate file, a user of the class can just #include the header and doesn't need to bother with the *.cpp file.
(Note that the *.cpp file, too, needs to #include its corresponding header file.)
If that looks complicated to you, view it from a different perspective. It allows you to modify the definition of the members without users of your class having to recompile their code. This is a big advantage of C++ compared to Java! The larger your project, the more important an advantage it becomes.
The general way of doing this in c++ with inheritance/polymorphism is by stating the following:
#include "myheaderfile.h"
I've got two questions.
Question 1: Can someone provide an example of how to define/redefine a variable in a namespace. I've provided my own guess for you to base an your answer from.
// namespace.hpp
namespace example
{
static string version;
static int x;
}
And then in a .cpp how do I redefine those variables?
// namespace.cpp
namespace example
{
version = "0.1"; // ?????
x = 0; //???
}
Question 2: How would I attach a permanent class object onto a namespace from the same .hpp file? Something like this:
// namespace.hpp
class Idk
{
public:
int doThis();
}
namespace example
{
Idk idkObject;
}
The code above, when included multiple times (from different files) will replace the object, which will cause compilation errors. Once again, I need a permanent way to attach a object to a namespace its header file.
Instead of 'static', write 'extern' in the header file and include the data type in the variable definitions in the cpp file.
Question 1: You need to specify the type also
// namespace.cpp
namespace example
{
string version = "0.1"; // ?????
int x = 0; //???
}
Question 2: You shouldn't create a 'non-static' object in a header file irrespective of the namespace. You should just use static here also or else you should use extern in header file and define the variable inside a cpp file. {Note it's a little different with templatized classes}
// namespace.hpp
class Idk
{
public:
int doThis();
}
namespace example
{
static Idk idkObject;
}
// namespace.cpp
namespace example
{
Idk idkObject; // Default constructor
}
I am programming on linux using g++ and I often encounter the problem that I need to use a class or data type in a header file which I define later, either at a later point in the header or in another header file.
For instance look at this header file:
class example
{
mydatatype blabla;
};
struct mydatatype
{
int blablainteger;
char blablachar;
};
This will give error because mydatatype is used before its defined
so usually I change it like this:
struct mydatatype; // <-- class prototype
class example
{
mydatatype *blabla; // <-- now a pointer to the data type
// I will allocate the data during runtime with the new operator
};
struct mydatatype
{
int blablainteger;
char blablachar;
};
Now it works. I could often just put the definition above, or include the header which is needed, but I don't want to include headers in a header or juggle with the definition order, it always gets messy.
The solution I showed usually works, but now I have encountered a new phenomenon. This time the datatype is not a class but a typedef, I cant use prototypes for a typedef and I don't want to use the actual datatype which the typedef incorporates.. it's messy too.
Is there any solution to this?
Firstly, the solution you've thought of (prototype and pointer), is unneeded, and slower than just implementing it without the pointer.
The "proper" solution for this, would be creating seperate headers for each type, and then include them in your other header. That way it will always be defined! You can even make them so that they include eachother.
However, if you've ever opened a .h file provided by g++, you've most likely seen this at the start of the header:
#ifndef SOMETHING_H
#define SOMETHING_H
// Code
#endif /* SOMETHING_H */
This is to solve the issue of types redefining themselves.
If they weren't there, and you included the header file multiple times, the types would be redefined, and an error would be thrown. This makes it so that the types are always present, but never included twice.
I hope that helps!
Place each class/type in it's own header file, and then include the relevant header file in other headers where you need it. Use an inclusion guard in each header e.g.:
// SomeHeaderFile.h
#ifndef SOME_HEADER_FILE_H
#define SOME_HEADER_FILE_H
// code
#endif
I disagree that this is messy - it allows you have an organised structure to you project, it allows each class to operate independently of others and without worrying about order, and it's a good idea to place each class in it's own file anyway.
You could just define the class inside the other class like
template<class T>
class vertex {
private:
class edge {
public:
vertex<T> *to;
double weight;
edge() {
weight = INFINITY;
to = NULL;
};
} *paths;
T data;
unsigned nof_paths;
public:
vertex(T val) {
data = val;
paths = NULL;
nof_paths = 0;
}
void addPathTo(vertex<T>*&);
edge* getAllPaths() {
return paths;
};
};
Obviously this works for small classes... if your class is ENORMOUS you'll be better using separate header files like the other guys said.