a function follow by const

M

moongeegee

press the send by mistake.

What does the "const" mean/purpose ?? Thanks.

class xxx
{
double getNum() const;
}
 
M

moongeegee

Sent by mistake.

What does the "const" mean/purpose ?? Thanks

class xxx
{
double getNum() const;
}
 
V

Vincent Jacques

moongeegee a écrit :
Sent by mistake.

What does the "const" mean/purpose ?? Thanks

class xxx
{
double getNum() const;
}

it means that, is you have a const instance of the class xxx, you will
be able to call getNum on it:

const xxx theXXX;
double d = theXXX.getNum();

When you declare a member function as const, the compiler check that the
function does not modify the object it is called on.

You can see those const functions as 'observers' of you class, or
'getters' (hence the name 'getYYY')

Cheers,
 
J

James Kanze

moongeegee a écrit :
it means that, is you have a const instance of the class xxx,
you will be able to call getNum on it:
const xxx theXXX;
double d = theXXX.getNum();
When you declare a member function as const, the compiler
check that the function does not modify the object it is
called on.

Formally, the const has two effects: you cannot call a non-const
function on an object designated by an expression with const
type (e.g. a const object, or a reference to const), and the
type of this in the function will be ClassName const*, rather
than simply ClassName* (i.e. you cannot modify the object in a
const function, with a few special exceptions).

Formally, too, the compiler applies what has usually been called
"bit-wise const": if your class is something like:

class C
{
char* p ;
public:
void f() const ;
} ;

C::f() can modify what p points to. Generally accepted
practice, however, is to implement logical const: if what p
points to is part of the "value" of your object, you don't
modify it in a const function, even if the compiler allows it.
(Similarly, if some direct member of your object is not part of
its conceptual value, you may modify it in a const function,
either by declaring it mutable or casting away const. This case
occurs far less frequently, however.)
 

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

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top