开发者

constant function [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicates:

What is the meaning of a const at end of a membe开发者_JS百科r function?

about const member function

I found one function prototype as under:

const ClassA* ClassB::get_value() const

What does the above statement signify? Can I change the member of ClassA object?


The first const means what it returns is a pointer to const A. So no, you can't change what it returns (unless you cast away the const-ness, which will give undefined behavior if the object it returns is actually defined as const, rather than returning a const pointer to an object that itself wasn't defined as const).

The second const means that get_value can't change any of the (non-mutable) state of the ClassB on which it's invoked (among other things, it's transitive, so ClassB::get_value can only call other member functions that are also const-qualified).


No.

The ClassA pointer returned by that function is marked const. That means that you should not change any of its values.

It won't be impossible to change the values because there are various ways to get around a const marking, but you are clearly not meant to be changing it.


What does the above statement signify? Can i change the member of ClassA object.

get_value is a const member function of ClassB so it cannot modify any non-mutable data members of ClassB inside its definition. But it can however modify members of ClassA

For example the following compiles (leaks memory but that is not much of a concern here)

struct A{

   int x;
};

struct B
{
   const A* get_value() const
   {
       A *p= new A;
       p->x = 12;
       return p;
    }
};


get_value() is a read-only function that does not modify the ClassB object for which it is called. It returns a read-only pointer to a ClassA object. You can modify the object pointed to by this object by casting away its constness using const_cast. But the ideal thing to do is to make a copy of this object and mutate that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜