Redefinition of Class after Separating to .h/.cpp - c++

I know this is a commonly asked question about C++ but following advice of other answers and such, I am still unable to get my seemingly simple code to work. My problem is the following code gives "error: redefinition of 'class Communicator'":
global.h
#ifndef GLOBAL_H
#define GLOBAL_H
class object_payload;
class pending_frame;
class Communicator {
private:
map<string,object_payload*> local_objects;
map<string,pending_frame*> remote_tasks;
bool listening;
public:
Communicator();
void stop_listening();
void add_to_remote_tasks(string name, pending_frame* pfr);
void listen();
void distributed_release(string task_name);
};
extern Communicator communicator;
#endif
global.cpp
#include "global.h"
class Communicator {
private:
map<string,object_payload*> local_objects;
map<string,pending_frame*> remote_tasks;
bool listening;
public:
Communicator(){
// implementation
}
void stop_listening(){
// implementation
}
void add_to_remote_tasks(string name, pending_frame* pfr){
// implementation
}
void listen(){
// implementation
}
void distributed_release(string task_name){
// implementation
}
};
Communicator communicator;
Does anyone know why this would be giving this error? The .cpp includes the header. I have other .cpp files that also include the header, but with the guard I don't see why that would matter.
Thanks for any help on this, much appreciated.
EDIT: Also, my runner.cpp file (with main) includes global.h in order to access the communicator global object.

You must have only one definition of a class. Currently you get one from #include and another in the file.
You shall not repeat the class itself, just implement the functions out of class, like
Communicator::Communicator(){
// implementation
}

That's not how you do the separation. The class (i.e. the declaration) goes into the header; the CPP file should have method implementations, like this:
Communicator::Communicator() {
...
}
void Communicator::stop_listening() {
...
}
and so on. Note the Communicator:: part of the fully qualified name: this is what tells the compiler that the function that you are defining belongs to the Communicator class.

In your cpp file you only need to define the functions that were declared but not defined in the header and scope them to your class:
Communicator::Communicator(){
// implementation
}
void Communicator::stop_listening(){
// implementation
}
void Communicator::add_to_remote_tasks(string name, pending_frame* pfr){
// implementation
}
void Communicator::listen(){
// implementation
}
void Communicator::distributed_release(string task_name){
// implementation
}

You define the class Communicator in the header file, and then try to add to it in the .cpp file. You can't do that in C++ - all the parts of the class definition must be in the same place.
Your header file should probably contain all the member definitions and function declarations, and your .cpp should proceed to define the member functions like:
void Communicator::stop_listening() { ... }

Related

Class redefinition: How to wrap methods within class [duplicate]

Is there a way to avoid the Graph:: repetition in the implementation file, yet still split the class into header + implementation? Such as in:
Header File:
#ifndef Graph_H
#define Graph_H
class Graph {
public:
Graph(int n);
void printGraph();
void addEdge();
void removeEdge();
};
#endif
Implementation File:
Graph::Graph(int n){}
void Graph::printGraph(){}
void Graph::addEdge(){}
void Graph::removeEdge(){}
I'm guessing this is to avoid lots of "unnecessary typing". Sadly there's no way to get rid of the scope (as many other answers have told you) however what I do personally is get the class defined with all my function prototypes in nice rows, then copy/paste into the implementation file then ctrl-c your ClassName:: on the clip board and run up the line with ctrl-v.
If you want to avoid typing the "Graph::" in front of the printGraph, addEdge etc., then the answer is "no", unfortunately. The "partial class" feature similar to C# is not accessible in C++ and the name of any class (like "Graph") is not a namespace, it's a scope.
No there's not. Not directly at least. You could go for preprocessor tricks, but don't do it.
#define IMPL Graph::
IMPL Graph(int n){}
void IMPL printGraph(){}
void IMPL addEdge(){}
void IMPL removeEdge(){}
Also, you shouldn't even want to do it. What's the point. Besides it being a C++ rule, it lets you know you're actually implementing a member function.
One option is using. If you have method definitions which are in a cpp file that never gets #included, then using is safe (doesn't affect other files):
foo.h:
class FooLongNameSpecialisationsParamaters
{
int x_;
public:
int Get () const;
void Set (int);
};
foo.cpp:
#include "foo.h"
using Foo = FooLongNameSpecialisationsParamaters;
int Foo::Get () const
{
return x_;
}
void Foo::Set (int x)
{
x_ = x;
}
main.cpp:
#include "foo.h"
int main ()
{
//Foo foo; <-- error
FooLongNameSpecialisationsParamaters foo;
return 0;
}
No, there is no way to avoid it. Otherwise, how would you know if a given function definition is for a class function or for a static function?
If you are asking if you can define a member function such as Graph::printGraph without specifying the class name qualification, then the answer is no, not the way that you want. This is not possible in C++:
implementation file:
void printEdge(){};
The above will compile just fine, but it won't do what you want. It won't define the member function by the same name within the Graph class. Rather, it will declare and define a new free function called printEdge.
This is good and proper, if by your point of view a bit of a pain, because you just might want two functions with the same name but in different scopes. Consider:
// Header File
class A
{
void foo();
};
class B
{
void foo();
};
void foo();
// Implementation File
void foo()
{
}
Which scope should the definition apply to? C++ does not restrict you from having different functions with the same names in different scopes, so you have to tell the compiler what function you're defining.
//yes it is possible using preprocessor like this:
#define $ ClassName //in .cpp
void $::Method1()
{
}
//or like this: in the header .h:
#undef $
#define $ ClassName'
// but you have to include the class header in last #include in your .cpp:
#include "truc.h"
#include "bidule.h" ...
#include "classname.h"
void $::Method() { }
//i was using also
#define $$ BaseClass
//with single inheritance than i can do this:
void $::Method()
{
$$::Method(); //call base class method
}
//but with a typedef defined into class like this it's better to do this:
class Derived : Base
{
typedef Base $$;
}
EDIT: I misread your question. This would be an answer to the question whether you can split header-files. It doesn't help you to avoid using LongClassName::-syntaxes, sorry.
The simple answer: You can split up c++-file, but you can not split up header-files.
The reason is quite simple. Whenever your compiler needs to compile a constructor, it needs to know exactly how many memory it needs to allocate for such an object.
For example:
class Foo {
double bar; //8 bytes
int goo; //4 bytes
}
new Foo() would require the allocation of 12 bytes memory. But if you were allowed to extend your class definitions over multiple files, and hence split header files, you could easily make a mess of this. Your compiler would never know if you already told it everything about the class, or whether you did not. Different places in your code could have different definitions of your class, leading to either segmentation faults or cryptic compiler errors.
For example:
h1.h:
class Foo {
double bar; // 8 bytes
int goo; // 4 bytes
}
h2.h:
#include "h1.h"
class Foo {
double goo; // 8 bytes
} // we extend foo with a double.
foo1.cpp:
#include "foo1.h"
Foo *makeFoo() {
return new Foo();
}
foo2.cpp:
#include "foo2.h"
void cleanupFoo(Foo *foo) {
delete foo;
}
foo1.h:
#include "h1.h"
Foo *makeFoo();
foo2.h:
#include "h1.h"
#include "h2.h"
void cleanupFoo(Foo *foo)
main.cpp:
#include foo1.h
#include foo2.h
void main() {
Foo *foo = makeFoo();
cleanupFoo(foo);
}
Carefully check what happens if you first compile main.cpp to main.o, then foo1.cpp to foo1.o and foo2.cpp to foo2.o, and finally link all of them together. This should compile, but the makeFoo() allocates something else then the cleanupFoo() deallocated.
So there you have it, feel free to split .cpp-files, but don't split up classes over header files.

C++ member function definition outside the class | duplicate symbols

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;
}

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 }

Is it possible to avoid repeating the class name in the implementation file?

Is there a way to avoid the Graph:: repetition in the implementation file, yet still split the class into header + implementation? Such as in:
Header File:
#ifndef Graph_H
#define Graph_H
class Graph {
public:
Graph(int n);
void printGraph();
void addEdge();
void removeEdge();
};
#endif
Implementation File:
Graph::Graph(int n){}
void Graph::printGraph(){}
void Graph::addEdge(){}
void Graph::removeEdge(){}
I'm guessing this is to avoid lots of "unnecessary typing". Sadly there's no way to get rid of the scope (as many other answers have told you) however what I do personally is get the class defined with all my function prototypes in nice rows, then copy/paste into the implementation file then ctrl-c your ClassName:: on the clip board and run up the line with ctrl-v.
If you want to avoid typing the "Graph::" in front of the printGraph, addEdge etc., then the answer is "no", unfortunately. The "partial class" feature similar to C# is not accessible in C++ and the name of any class (like "Graph") is not a namespace, it's a scope.
No there's not. Not directly at least. You could go for preprocessor tricks, but don't do it.
#define IMPL Graph::
IMPL Graph(int n){}
void IMPL printGraph(){}
void IMPL addEdge(){}
void IMPL removeEdge(){}
Also, you shouldn't even want to do it. What's the point. Besides it being a C++ rule, it lets you know you're actually implementing a member function.
One option is using. If you have method definitions which are in a cpp file that never gets #included, then using is safe (doesn't affect other files):
foo.h:
class FooLongNameSpecialisationsParamaters
{
int x_;
public:
int Get () const;
void Set (int);
};
foo.cpp:
#include "foo.h"
using Foo = FooLongNameSpecialisationsParamaters;
int Foo::Get () const
{
return x_;
}
void Foo::Set (int x)
{
x_ = x;
}
main.cpp:
#include "foo.h"
int main ()
{
//Foo foo; <-- error
FooLongNameSpecialisationsParamaters foo;
return 0;
}
No, there is no way to avoid it. Otherwise, how would you know if a given function definition is for a class function or for a static function?
If you are asking if you can define a member function such as Graph::printGraph without specifying the class name qualification, then the answer is no, not the way that you want. This is not possible in C++:
implementation file:
void printEdge(){};
The above will compile just fine, but it won't do what you want. It won't define the member function by the same name within the Graph class. Rather, it will declare and define a new free function called printEdge.
This is good and proper, if by your point of view a bit of a pain, because you just might want two functions with the same name but in different scopes. Consider:
// Header File
class A
{
void foo();
};
class B
{
void foo();
};
void foo();
// Implementation File
void foo()
{
}
Which scope should the definition apply to? C++ does not restrict you from having different functions with the same names in different scopes, so you have to tell the compiler what function you're defining.
//yes it is possible using preprocessor like this:
#define $ ClassName //in .cpp
void $::Method1()
{
}
//or like this: in the header .h:
#undef $
#define $ ClassName'
// but you have to include the class header in last #include in your .cpp:
#include "truc.h"
#include "bidule.h" ...
#include "classname.h"
void $::Method() { }
//i was using also
#define $$ BaseClass
//with single inheritance than i can do this:
void $::Method()
{
$$::Method(); //call base class method
}
//but with a typedef defined into class like this it's better to do this:
class Derived : Base
{
typedef Base $$;
}
EDIT: I misread your question. This would be an answer to the question whether you can split header-files. It doesn't help you to avoid using LongClassName::-syntaxes, sorry.
The simple answer: You can split up c++-file, but you can not split up header-files.
The reason is quite simple. Whenever your compiler needs to compile a constructor, it needs to know exactly how many memory it needs to allocate for such an object.
For example:
class Foo {
double bar; //8 bytes
int goo; //4 bytes
}
new Foo() would require the allocation of 12 bytes memory. But if you were allowed to extend your class definitions over multiple files, and hence split header files, you could easily make a mess of this. Your compiler would never know if you already told it everything about the class, or whether you did not. Different places in your code could have different definitions of your class, leading to either segmentation faults or cryptic compiler errors.
For example:
h1.h:
class Foo {
double bar; // 8 bytes
int goo; // 4 bytes
}
h2.h:
#include "h1.h"
class Foo {
double goo; // 8 bytes
} // we extend foo with a double.
foo1.cpp:
#include "foo1.h"
Foo *makeFoo() {
return new Foo();
}
foo2.cpp:
#include "foo2.h"
void cleanupFoo(Foo *foo) {
delete foo;
}
foo1.h:
#include "h1.h"
Foo *makeFoo();
foo2.h:
#include "h1.h"
#include "h2.h"
void cleanupFoo(Foo *foo)
main.cpp:
#include foo1.h
#include foo2.h
void main() {
Foo *foo = makeFoo();
cleanupFoo(foo);
}
Carefully check what happens if you first compile main.cpp to main.o, then foo1.cpp to foo1.o and foo2.cpp to foo2.o, and finally link all of them together. This should compile, but the makeFoo() allocates something else then the cleanupFoo() deallocated.
So there you have it, feel free to split .cpp-files, but don't split up classes over header files.

C++ accessing a function from in a class, receiving functions as a parameter

i have two questions that are fairly small and related so i will put them both in the same question.
i have been experimenting with classes and i was attempting to access a class in another file that wasn't in a class so for example.
//class 1 .cpp
void Class1::function1()//another error
{
function()
}
//main.cpp
void function()
{
//stuff happens
}
is there a way to-do this? or would i need to add this function to a class to get it to work. also how would you go about creating a function that receives a function as it parimetre? for example function(function2())
i am simply trying to access a function from a class as it would make my code easier to use later if the function that i am using doesn't get added to a class. with regards to the seconds question i which to create a function that receives a time and a function as an argument. it will wait for the specified time then execute the program
How to access a function in another file?
Depends on the type of function, there can be to cases:
1. Accessing class member functions in another file(Translation Unit):
Obviously, you need to include the header file, which has the class declaration in your caller translation unit.
Example code:
//MyClass.h
class MyClass
{
//Note that access specifier
public:
void doSomething()
{
//Do something meaningful here
}
};
#include"MyClass.h" //Include the header here
//Your another cpp file
int main()
{
MyClass obj;
obj.doSomething();
return 0;
}
2. Accessing free functions in another file(Translation Unit):
You do not need to include the function in any class, just include the header file which declares the function and then use it in your translation unit.
Example Code:
//YourInclude.h
inline void doSomething() //See why inline in #Ben Voight's comments
{
//Something that is interesting hopefully
}
//Your another file
#include"YourInclude.h"
int main()
{
doSomething()
return 0;
}
Another case as pointed out by #Ben in comments can be:
A declaration in the header file, followed by a definition in just one translation unit
Example Code:
//Yourinclude File
void doSomething(); //declares the function
//Your another file
include"Yourinclude"
void doSomething() //Defines the function
{
//Something interesting
}
int main()
{
doSomething();
return 0;
}
Alternately, a messy way to do this can be to just mark the function as extern in your another file and use the function.Not recommended but a possibility so here is how:
Example Code:
extern void doSomething();
int main()
{
doSomething();
return 0;
}
How would you go about creating a function that receives a function as it parameter?
By using function pointers
In a nutshell Function pointers are nothing but pointers but ones which hold address of functions.
Example Code:
int someFunction(int i)
{
//some functionality
}
int (*myfunc)(int) = &someFunction;
void doSomething(myfunc *ptr)
{
(*ptr)(10); //Calls the pointed function
}
You need a prototype for the function you want to call. A class body contains prototypes for all its member functions, but standalone functions can also have prototypes. Typically you organize these in a header file, included from both the file which contains the function implementation (so the compiler can check the signature) and in any files which wish to call the function.
(1) How can the `class` function be accessible ?
You need to declare the class body in a header file and #include that wherever needed. For example,
//class.h
class Class1 {
public: void function1 (); // define this function in class.cpp
};
Now #include this into main.cpp
#include"class.h"
You can use function1 inside main.cpp.
(2) How to pass a function of class as parameter to another function ?
You can use pointer to class member functions.