htd
htd

Reputation: 331

Question about specific placemenet of const keyword in overloaded -> operator

Consider the following "smart pointer" like class. It holds a pointer to another class that has implemented a virtual copy constructor clone().

I want to overload the operator ->. My source shows two implementations, a const and non-const one - which I'm fine with. I understand that the latter const means it cannot make changes to the underlying field variables and the former that the return type is const. But what does the keyword between the return type and operator mean? - i.e. the middle one.

class myClass
{
public:
    myClass(const SomeClass& inner)   {DataPtr = inner.clone();}
    ~MyClass() {delete DataPtr;}
    SomeClass* operator->() {return DataPtr;} 
    const SomeClass* const operator->() const {return DataPtr;}
private:
    SomeClass* DataPtr;
};

Upvotes: 0

Views: 64

Answers (2)

eerorika
eerorika

Reputation: 238401

and the former that the return type is const

Actually, no. The former (i.e. the first const of const SomeClass* const) means that the return type is pointer to const. This means that the pointed object cannot be modified using the pointer.

But what does the keyword between the return type and operator mean?

It is part of the type.

const in a type name always applies to what is on the left side (except when the const is the left most token, in which case it applies to the right). In this case, there is an * on the left side of the const that we're considering. This means that the pointer is const i.e. the pointer itself cannot be modified.

It is not sensible to return a non-class type const value (in this case, a const pointer), because the constness has has no effect on the behaviour of the program. Some compilers will issue a warning if you do this. I recommend removing the const in question.

Even for class types, while it might make a difference in some case, I don't know of any practical use case for returning a const value. Returning a pointer or a reference to const does make sense however.

Upvotes: 1

Vittorio Romeo
Vittorio Romeo

Reputation: 93324

const SomeClass* const

In this case, const is part of the return type. This can be valid C code. As always, read from right to left:

  • const pointer to a const SomeClass instance.

This means that the pointer itself is const, and that the pointee cannot be modified through it. Note that the rightmost const is useless in your example as you're returning by value: it's the same as returning const int.

Upvotes: 1

Related Questions