I have the following header:
class MyClass {
private:
static void (*OnRequest)();
static void (*OnReceive)(int numBytes);
public:
MyClass();
static void SetOnReceive(void (*function)(int));
static void SetOnRequest(void (*function)(void));
};
void NonClassFunction();
and the following declaration:
#include "MyClass.h"
MyClass::MyClass() {
...
}
void MyClass::SetOnReceive(void (*function)(int) ) {
OnReceive = function;
}
void MyClass::SetOnRequest( void (*function)(void) ) {
OnRequest = function;
}
void NonClassFunction() {
MyClass::OnRequest();
}
The code compiles fine but I get the following errors when I link:
unresolved symbol MyClass::OnReceive, first referenced in ./src/MyClass.obj
unresolved symbol MyClass::OnRequest, first referenced in ./src/MyClass.obj
I need OnRequest and OnReceive to function like a callback through NonClassFunction(). The NonClassFunction is being called by an interrupt so there is a bit of object oriented mangling going on here. MyClass is designed to be inherited. Ideally I would like OnRequest and OnReceive to be virtual but you cannot make static methods virtual.
Those are linker error, which means the members are not defined. They're only declared.
The pointer members are static members, so they need definition, which is outside the class.
Do this in the .cpp file:
void (*MyClass::OnRequest)();
void (*MyClass::OnReceive)(int);
These are definitions, and what you've written in the class are only declarations.
Note the position of * in the above definitions. A slight mistake such as these:
void (MyClass::*OnRequest)(); //notice the difference
void (MyClass::*OnReceive)(int); //notice the difference
would change the meaning completely! Now these are pointers-to-non-static-member-function. So know the difference and be careful. :-)
These two variables in your header:
static void (*OnRequest)();
static void (*OnReceive)(int numBytes);
Have not been defined.
Define them in your cpp file.
void (*MyClass::OnRequest)();
void (*MyClass::OnReceive)(int);
You provided the declarations of the function pointers, but not the definition. Add this to a single cpp file:
void (*MyClass::OnRequest)();
void (*MyClass::OnReceive)(int);
i asked the same question recently
how-to-send-a-message-to-the-class-that-created-the-object
enemies_array[0].enemy = new Enemy(this,&Game::EnemyEvent);
typedef void (Game::*ChangeFunc)(DWORD &)
Class Enemy
{
private:
ChangeFunc iChange;
Game *pGame;
}:
Enemy(Game *pCreatorGame, ChangeFunc iChangeHandler )
{
iChange = iChangeHandler;
pGame = pCreatorGame;
}
void Enemy::Draw(D3DGraphics& gfx)
{
(pGame->*iChange)(this->dwThreadID);
Related
I am new to templates and I have searched the web for this error but I don't know how to fix it it.
Already checked Why can templates only be implemented in the header file?
State.h
template <class entityType>
class State
{
public:
State() = default;
virtual void Enter(entityType * owner);
};
EnterMine.h
#include "State.h"
class Miner;
class EnterMine : public State<Miner>
{
public:
EnterMine() = default;
virtual void Enter(Miner *) {
};
};
and Miner.cpp is blank
and the problem appears in main.cpp
#include "EnterMine.h"
int main()
{
EnterMine a;
}
The error I get is a linking error :
LNK2001 unresolved external symbol "public: virtual void __thiscall State::Enter(class Miner *)" (?Enter#?$State#VMiner####UAEXPAVMiner###Z)
(Note: this answer was written for the original question, it has been completely rewritten after that.)
Every function that is declared and used, should be defined somewhere.
It seems that you declare EnterMine::EnterMine() but never define it. If this constructor does nothing, either omit it (it will be implicitly defined by a compiler), or mark it as = default;.
class EnterMine : public State<Miner>
{
public:
EnterMine() = default;
...
};
This also applies to the State::State() constructor.
Even though it's a singleton, you're still calling the constructor. Thus, you will still need to define the constructor.
In fact, you need to define every function you declare in your header.
I am currently very new to c++, i have started learning how to use pointers in a path finding algorithm.
I am having an issue with calling a function within a class that is derived from a base class.
The specific piece of code causing issue is:
FreeTile *tempPointer = new FreeTile();
cout<<tempPointer->getFree()<<endl;
mapp[i][j] = tempPointer;
when i call getFree (which returns a boolean value) i get the error:
undefined reference to Tile::getFree(). Tile being the base class.
The header for FreeTile is:
#ifndef FREETILE_H
#define FREETILE_H
#include "Tile.h"
class FreeTile:public Tile
{
public:
FreeTile();
virtual ~FreeTile();
void setParent(FreeTile* par);
int getF();
int getG();
int getH();
void setF(int in);
void setG(int in);
void setH(int in);
FreeTile* getParent();
protected:
private:
int F;
int G;
int H;
bool free;
};
Tile header is:
#ifndef TILE_H
#define TILE_H
class Tile
{
public:
Tile();
virtual ~Tile();
bool getFree();
void setFree(bool bo);
protected:
private:
bool free;
};
#endif // TILE_H
#endif // FREETILE_H
Finally the cpp file for Tile:
#include "Tile.h"
#include <iostream>
using namespace std;
bool free;
Tile::Tile()
{
cout<<"Constructor Called"<<endl;
}
Tile::~Tile()
{
//dtor
}
bool getFree(){
return free;
}
void setFree(bool bo){
free = bo;
}
If you need more code or if im missing something blatant feel free to shame me as much as you like :P
Thanks in advance.
On a side note, can you initiate a private variable in a constructor such as free = true as when doing this it states the variable is private.
In the Cpp file rename "bool getFree()" to
"bool Tile::getFree()"
In your implementation the function is just a regular c gloabl function.
In the fixed version it is the class function implementaion of the function you declare in the header file
Also
1st in your Tile you have a private variable "bool free"
in the cpp file you have a global variable "bool free"
this is confusing.
Probably want to delete the one you declared in the cpp file.
Want a deeper explanation?
Yeah! my 1st answer!
Deeper Explanation:
the function you declared in the Class Tile is not defined (just declared) because you didn't add "Tile::" before the function definition in the cpp file (i.e you didn't define a scope).
The function you wrote in the cpp file is both defined and declared in the cpp file, so only functions written after it in the cpp file can call it (works same a c).
Probably when you wrote the function it didn't know that "free" was, right? because it was not a class function. so you added the global "bool free" but that is a completely different variable.
Glad to help!
don't forget to mark this as answered!
I feel confused with whether there is a need to set up a class for one or several functions. I give the following example to make my point clear:
file1.h
void Fun1();
void Fun2();
file1.cpp
void Fun1() {}
void Fun2() {}
As you can see we have two functions here, and people using these functions just need to include the header file and then call them. Then, I also have the choice of setting up a class without any member variables insider but only for these two functions (suppose these two functions are closely related):
file1.h
class Operation
{
Operation() {};
~Operation() {};
void Fun1();
void Fun2();
};
file1.cpp
void Operation::Fun1() {};
void Operation::Fun2() {};
Then my question is which practice is better and why. Thanks.
You should use a dedicated namespace
file1.h:
namespace MyDedicatedNameSpace
{
void Fun1();
void Fun2();
}
file1.cpp:
void MyDedicatedNameSpace::Fun1() {}
void MyDedicatedNameSpace::Fun2() {}
Or if you want to use a class, you should set these functions as static:
file1.h:
class Operation
{
public:
static void Fun1();
static void Fun2();
};
file1.cpp:
void Operation::Fun1() {};
void Operation::Fun2() {};
You don't "have to" put them in a class, you can go for both implementations. It's mostly a design preference. Java coders are used to putting those functions as static functions of a utility class, but in C++ you don't have to, although some people do.
If your concern is just encapsulation of those functions in a specific context, you might also consider putting them in namespaces.
There should be a reason you want to put them in one class.
If it's just for grouping, namespace better suits for this role.
file1.h
namespace Operation
{
void Fun1();
void Fun2();
};
file1.cpp
namespace Operation
{
void Fun1(){};
void Fun2(){};
};
P.S. If for some reason you would still prefer to use class, make functions static at least, so you wouldn't need to create an instance of this class.
file1.h
class Operation
{
public:
static void Fun1();
static void Fun2();
};
file1.cpp
void Operation::Fun1() {};
void Operation::Fun2() {};
Since you asked specifically about C++, the most correct answer would be to namespace them:
file1.h:
namespace MyNamespace
{
void Fun1();
void Fun2();
}
file1.cpp:
namespace MyNamespace
{
void Fun1() {}
void Fun2() {}
}
Then to use them you would simply call MyNamespace::Fun1() etc.
As I started out saying, this is most correct for C++.
If you were writing this for C, or mixed C/C++ it should be noted that C does not support namespaces. So in that case making them static functions of a class would be a better organizational route.
file1.h
class MyClass
{
public:
static void Fun1();
static void Fun2();
};
file1.c
void MyClass::Fun1() { }
void MyClass::Fun2() { }
NOTE: if you are doing mixed programming you should consider making it easier to include, but that's beyond the scope of this question.
If I implement the create method of the class in .cpp I get
error LNK2019: unresolved external symbol "protected: __thiscall Singleton::Singleton(void)" (??0Singleton##IAE#XZ) referenced in function "public: static void __cdecl Singleton::create(void)" (?create#Singleton##SAXXZ
However if I implement the method inside the header file it compiles without any error :S
header file
#pragma once
#include <iostream>
class Singleton
{
public:
static Singleton * getInstance()
{
return s_instance;
}
static void create();
static void destroy();
void help();
protected:
static Singleton * s_instance;
Singleton();
};
source file:
#include "Singleton.h"
Singleton * Singleton::s_instance = NULL;
void Singleton::create()
{
if (!s_instance)
{
s_instance = new Singleton;
}
}
void Singleton::destroy()
{
delete s_instance;
s_instance = NULL;
}
However If I implement the create method inside the header it does not throws any error
Header file with create method implemented in it
#pragma once
#include <iostream>
class Singleton
{
public:
static Singleton * getInstance()
{
return s_instance;
}
static void create(){
if (!s_instance)
{
s_instance = new Singleton;
}
}
static void destroy();
protected:
static Singleton * s_instance;
Singleton();
};
In cpp, your create function is trying to initialize Singleton, by using new operator, but you dont give it an constructor. Try to give an implementation to Singleton(). i.e.:
protected:
static Singleton * s_instance;
Singleton() {}
};
The problem.
You have declared a default constructor, and you're using it (in a new expression), but you haven't implemented it.
Fix.
Simply remove the constructor declaration:
protected:
static Singleton * s_instance;
// Singleton(); -- don't have this. Remove it.
};
Other matters.
With protected features the class is designed for inheritance, so how does one ensure that a derived class can only be instantiated via the singleton machinery?
Well you don't have much control over derived classes, so the easiest is just to document that each derived class should declare and define a non-public default constructor.
However, there is a trick that can be used to enforce this, based on the fact that a virtual base must be initialized by the most derived class. This can be used to force client code to add a final class derivation at bottom. Where that most derived class is a template instantiation, which defines a non-public constructor.
A more practical alternative is to turn things upside-down.
That is, instead of designing the Singleton class for derivation (signalled by protected stuff), design it to inherit from a client code class. Again this means using templates. Andrei Alexandrescu discussed a number of singleton approaches using this idea, in his classic book “Modern C++ Design”.
class Base
{
private:
static int num;
public:
friend void setnum(Base obj);
};
void setnum(Base obj)
{
obj.num=4; /* Error */
}
A friend function is supposed to have access to all the private data of a class. what am i missing here? I cant seem to access the the static variable from the friend function.
Error from codepad--> In function
setnum(Base)': undefined reference to
Base::num'
Error from visual studio--> error LNK2001:
unresolved external symbol "private:
static int Base::num"
You only declared the static variable num. You must to define it:
class Base
{
private:
static int num;
public:
friend void setvals(Base obj);
};
// This must be in a .cpp
int Base::num;
void setvals(Base obj)
{
obj.num=4;
}
This code works.
Edit:
Actually you can implement the setvals() function as follows:
void setvals()
{
Base::num=4;
}
And at your Base class:
friend void setvals();
Because num is static.
Your free function is called setvals, but the Base's friend function is called setnum...
Besides you'll have to actually define the static variable, not just declare it.
Put:
int Base::num;
in a source file.
Different friends:
friend void setnum(Base obj);
// ^^^ Not the same as vals!
void setvals(Base obj)
In C++ it's not enough to declare a static variable in the .h; you must also define it explicitly in a .cpp. You must add in the .cpp of the implementation
int Base::num;
What you got was a linker error because of this missing variable definition.
Static variables don't belong to any particular instance of a class. Instead you may access them with a class name as Base::num to improve readability. Also, your friend function definition has a different signature than the one you declared.