0

Possible Duplicates:
What is the meaning of a const at end of a member 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?

Community
  • 1
  • 1
boom
  • 5,856
  • 24
  • 61
  • 96
  • 1
    Possible duplicate: http://stackoverflow.com/questions/1966319/about-const-member-function – Dante May Code Mar 18 '11 at 05:04
  • Is your question, can I change members of a const object? I presume you aren't the writer of get_value and aren't trying to change the ClassA object from within the body of the function. – grantnz Mar 18 '11 at 05:05

4 Answers4

2

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).

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
1

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.

Zan Lynx
  • 53,022
  • 10
  • 79
  • 131
1

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;
    }
};
Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
  • @Saurav: This means the return object(A*) by method get_value() can modify the value of x, which is its member.Is that right? – boom Mar 18 '11 at 05:58
  • No you can't change what the function returns because the return type is `const ClassA*` and not `ClassA*` – Prasoon Saurav Mar 18 '11 at 06:00
0

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.

Vijay Mathew
  • 26,737
  • 4
  • 62
  • 93