1

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?

user2864740
  • 60,010
  • 15
  • 145
  • 220
KKlouzal
  • 732
  • 9
  • 32

1 Answers1

5

The problem is that in the callback, the DataPacket object Packet is marked as const. That means you can't call non-const function in the object.

This can simply be changed by making the GetData member function const, and no it's not what you have done, you have only made the returned integer const, which makes no sense (because the value will just be copied and loose it's const-ness).

Instead declare the function as

int GetData() const;
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Thank you very much, this was the solution. Can I ask what is the difference in placing const at the end vs at the beginning? – KKlouzal Jul 18 '14 at 01:51
  • 1
    @KKlouzal If you place the `const` at the bginning (like you have in your question), then you make the *returned value* `const`, if you place it after the function, at the end, you make the *function* constant (i.e. telling the compiler that it will not change anything in the object). – Some programmer dude Jul 18 '14 at 02:37