Compile Error C2662 [duplicate] - c++

This question already has answers here:
c++ error C2662 cannot convert 'this' pointer from 'const Type' to 'Type &'
(4 answers)
Closed 8 years ago.
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?

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;

Related

compiler reports const instead of const& [duplicate]

This question already has answers here:
Does each expression in C++ have a non-reference type
(5 answers)
Is Expression type same as object, references, or functions type?
(2 answers)
Closed 4 months ago.
Tried to compile following code, can't understand error message.
#include<iostream>
#include<string>
using namespace std;
struct S {
string a{"abc"};
const string& data() { return a; }
};
int main() {
S s;
int a = s.data(); // error: no viable conversion from 'const std::string' to 'int'
return 0;
}
Question: why does compiler say 'const std::string' instead of 'const std::string&'?
Tried with Apple clang 14.0.0 and g++ 12, same error message.
data() returns a reference to a const std::string object, yes. But, you are not converting the reference itself to an int, you are converting the std::string object that it refers to.
A reference is just an alias, once a reference has been bound to an object, any access of the reference is really accessing the object instead.
That is why the error message does not include &.
Expressions (such as s.data()) never have reference types.
& is silently removed from the type, and, in case of a function call, dictates the value category of the resulting expression (lvalue in this case).

Const has no effect when passing class member by reference in c++ [duplicate]

This question already has answers here:
Why can a const method take a non const reference?
(2 answers)
Closed 2 years ago.
Consider the following code:
#include <iostream>
class ObjectCalculator {
public:
struct Object {
int id = 0;
};
void setObject(Object& object) const {
object.id = 1;
}
Object m_object;
};
int main() {
ObjectCalculator objCalc{};
std::cout << objCalc.m_object.id << std::endl;
objCalc.setObject(objCalc.m_object);
std::cout << objCalc.m_object.id << std::endl;
return 0;
}
I thought this this line should throw an error during compilation since the internal variable is changed via const method setObject:
objCalc.setObject(objCalc.m_object);
but the code compiles with no errors and outputs:
0
1
Could you please clarify why const does not have effect in this case?
const related to the members of the class.
You modifying the method argument, so it can be changed, regardless of const.
const after method applied to the implicit first method argument this, through which all class members accessed.
cppreference
A non-static member function can be declared with a const, volatile,
or const volatile qualifier (this qualifier appears after the
parameter list in the function declaration). Differently cv-qualified
functions have different types and so may overload each other.
In the body of a cv-qualified function, the this pointer is
cv-qualified, e.g. in a const member function, only other const member
functions may be called normally. (A non-const member function may
still be called if const_cast is applied or through an access path
that does not involve this.)
The const qualifier is to tell that the function does not modify this object.
By passing the object to modify as an argument you don't modify this, you modify the object passed as an argument.
If you tried to modify m_object in the function, you would get the error you expected.

is there a way to pass this as const?

I have a class of items and a function that returns it's size.
I have the operator == which gets 2 const parameters of the class type and return the result of item1.size() == item2.size (). size function is non-parametres func and need only hidden this parameter.
The problem is when I try to use size on const reference of classes, it's give me an error:
'function' : cannot convert 'this' pointer from 'type1' to 'type2'
The compiler could not convert the this pointer from type1to type2.
This error can be caused by invoking a non-const member function on a const object. Possible resolutions:
Remove the const from the object declaration.
Add const to the member function.
The piece of code as it is on my problem:
bool operator==(const CardDeck& deck1, const CardDeck& deck2){
if (deck1.size() != deck2.size()) {
return false;
}
//...
}
The error:
'unsigned int CardDeck::size(void)' : cannot convert 'this' pointer from 'const CardDeck' to 'Cardeck&'
If I want that size will get the object as const, I must make it friend and pass the object as const refference or is there a way to tell size get the class type this as constant ???
Thanks for helping.
Most likely you forgot to qualify the size member function as const: size_t size() const { return /* compute/return size */; }
The alternative is that you really did typo CardDeck as Cardeck somewhere (the spelling from your error message).

Why is an array argument treated as a const array?

I am working with a member function that just sets the object's internal orientation to the values given in the argument:
void A::SetOrientation(float a[3]);
In another class, I have the following:
class B
{
public:
RestoreStateTo(A* const o_pA) const
private:
float d_orientation[3];
};
void
B::RestoreStateTo(A* const o_pA) const
{
o_pA->SetOrientation(d_orientation);
}
I get the following compiler error (with Visual Studio 2010):
error C2664: 'void A::SetOrientation(float [])' : cannot convert parameter 1 from 'const float [3]' to 'float []'
I found that I can avoid the issue with o_pA->SetOrientation(const_cast<float *>(d_orientation));, but I'd like to get a better grasp of what is going on.
I would appreciate an explanation as to why the array argument is converted to a const array as well as suggest the right approach to dealing with the error?
Because the prototype of your function void B::RestoreStateTo(A* const o_pA) const says you will not modify any member of B.
Since d_orientation is an attribute of B, it is const in this function.
Your SetOrientation function should take in a const,
void A::SetOrientation(const float a[3]);
Otherwise, it's possible that A::SetOrientation will modify the array you pass in. Because you have "B::RestoreStateTo(A* const o_pA) const", it means that the compiler won't let you pass a pointer to B::d_orientation as a non-const input, because A::SetOrientation has no guarantee not to modify it.
You have declared a const member function, and therefore all the members of this will be treated as const inside that function. So it shouldn't be surprising that d_orientation is treated as const.
It's the same principle that makes this code illegal:
const B* p = ...;
p->d_orientation[0] = 0.0f; // error, assigning member of `const` object

Argument conversion for function taking an arg as 'const arg *&'

Here is a problem i am facing while reviving a old code
here is another one--
so here is definition of a function:-
int shen_get_entity_from_list(const ENTITY_LIST& list, const ENTITY*& e);
and here is the way that variables are defined
ENTITY *t_ent = NULL, *p_e = NULL, *s_e = NULL, *t_e = NULL;
now when i call this function
s_pos = shen_get_entity_from_list(sortedACISfeatureList, s_e);
it gives me the following error
error C2664: 'shen_get_entity_from_list' : cannot convert parameter 2 from 'ENTITY *' to 'const ENTITY *&'
The s_e variable needs to be declared as:
const ENTITY* s_e = NULL;
to match the declaration of the function. This says that you won't use the s_e pointer to modify the ENTITY that it points so after the function is called.
isn't the reference already const type? and requires value at creation time itself?
null pointer references aren't allowed.
because of all these i don't feel this problem is solvable
Try moving the const:
int shen_get_entity_from_list(const ENTITY_LIST& list, ENTITY* const& e);
This gives you a const-reference to the type you are passing, rather than a non-const reference to a pointer to a const ENTITY.