I'm trying to pass an object as a reference to a function that accepts the object as a const however the compiler is throwing:
error C2662: 'const int DataPacket::GetData(void)': cannot convert 'this' pointer from 'const DataPacket' to 'DataPacket &'
IntelliSense says:
the object has type qualifiers that are not compatible with the member function
object type is: const DataPacket
I made a test-cast of the code to demonstrate the issue:
#include <iostream>
#include <functional>
class DataPacket
{
int SomeVar;
public:
DataPacket(int InitialData)
{
SomeVar = InitialData;
}
const int GetData()
{
return SomeVar;
}
};
void ProcessPacket(const DataPacket& Packet)
{
std::cout << Packet.GetData() << std::endl;
}
int main()
{
std::function<void(const DataPacket& Packet)> f_Callback;
f_Callback = ProcessPacket;
while (true)
{
f_Callback(DataPacket(10));
}
}
Basically I have a STD function which the user can set to use their own callback function. A lower level class creates objects of type DataPacket when new packets arrive. I then want to pass the object into the callback function as a constant reference so not to copy the entire object and restrict the user from changing the original object.
What's going on here? How can I pass DataPacket into f_Callback as a const reference?