Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Const Confusion

Status
Not open for further replies.

RichardF

Programmer
Oct 9, 2000
239
GB
Hi,

I've just got over an hour long compile error. I fixed it, but I dont understand why. Can anyone help explain.


// Triangle is a nested class with-in this class
vector<Triangle> Triangles;
...

Code:
inline Triangle* get_Triangle(UINT Index) const {
	if (Index >= 0 && Index < Triangles.size()) 
		return &Triangles[Index]; // C2440
	else
		return NULL;
}

d:\Test\Test.cpp(85) : error C2440: 'return' : cannot convert from 'const std::allocator<_Ty>::value_type *__w64 ' to 'TriangleCollection::Triangle *'
with
[
_Ty=Triangulate2D::Triangle
]
Conversion loses qualifiers


If i remove the const then it compiles ok.
Thanks.

 
You should only make your class methods const if they do not modify the members of the class. By giving an error with the const specifier, the compiler is saying that returning a pointer to internal data breaks that rule. Notice how this simple code also causes a compile error:
Code:
class Test
{
public:
    Test() : data(0) { }
    int* getdata() const { return &data; }
private:
    int data;
};

int main()
{
}
It depends on what you are trying to achieve, but returning a copy of the Triangle, or a const reference to the Triangle, or a const_iterator to the Triangle's position in the vector are all potential alternatives beyond making the method non-const.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top