How to solve this problem regarding the const qualifier?

X

xz

I have a function foo as follows

void Foo::foo(const Vertex & a, const Vertex & b, const Vertex & c) {

Coordinate head;
a.calcSomething(......);
}

an got the following error information when compiling:

Foo.cpp:156: error: passing 'const Vertex' as 'this' argument of
'const void Vertex::calcSomething(......)' discards qualifiers


How to solve this problem? Isn't it enough to put calcSomething in the
following way?

class Vertex{
const void calcSomething(...){
....
};
};
 
I

Ian Collins

xz said:
I have a function foo as follows

void Foo::foo(const Vertex & a, const Vertex & b, const Vertex & c) {

Coordinate head;
a.calcSomething(......);
}

an got the following error information when compiling:

Foo.cpp:156: error: passing 'const Vertex' as 'this' argument of
'const void Vertex::calcSomething(......)' discards qualifiers


How to solve this problem? Isn't it enough to put calcSomething in the
following way?

class Vertex{
const void calcSomething(...){

No, the const is qualifying the return type. To make the function
const, write

void calcSomething() const;
 
D

DDD

I have a function foo as follows

void Foo::foo(const Vertex & a, const Vertex & b, const Vertex & c) {

        Coordinate head;
        a.calcSomething(......);

}

an got the following error information when compiling:

Foo.cpp:156: error: passing 'const Vertex' as 'this' argument of
'const void Vertex::calcSomething(......)' discards qualifiers

How to solve this problem? Isn't it enough to put calcSomething in the
following way?

class Vertex{
const void calcSomething(...){
...



};
};- Hide quoted text -

- Show quoted text -

But what're the parameters of calcSomething()?
 
M

Martin York

But what're the parameters of calcSomething()?

What?

The object 'a' is a constant. Therefore you can not call methods that
modify the object. The compiler enforces this by only allowing you to
call const methods on a const object.
 
A

Andy Champ

DDD said:
But what're the parameters of calcSomething()?

"this" is an implicit parameter to a call of any non-static method. if
"this" is const at the time, you have to mark the method "const" to show
that you aren't going to change it.

Andy
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top