Overdone declarations ?

  • Thread starter =?ISO-8859-1?Q?Mart_K=E4sper?=
  • Start date
?

=?ISO-8859-1?Q?Mart_K=E4sper?=

Hi,

suppose a collection type of class that might return references to
classes of type Object - it has (among others) access methods as follows:

virtual Object*& at(int) = 0;
virtual const Object *const& at(long) const = 0;

where the int and the long denote the internal order within the
collection, numbered from 0..[size-1]

My question is: what on earth does the second method return ? How come
anyone ever declares a method in that way ... would it be that bad to
rephrase it into the form of the first method ?

Thanks in advance :)
 
L

llewelly

Mart Käsper said:
Hi,

suppose a collection type of class that might return references to
classes of type Object - it has (among others) access methods as
follows:

virtual Object*& at(int) = 0;
virtual const Object *const& at(long) const = 0;

where the int and the long denote the internal order within the
collection, numbered from 0..[size-1]

My question is: what on earth does the second method return ?

It returns a reference which cannot be used to modify the pointer it
refers to, which pointer in turn cannot be used to modify the
Object it points to.

A decl of this sort must be read right-to-left:

const Object *const&

reads as: reference to const pointer to const Object.
How come
anyone ever declares a method in that way ...

Notice the member function is const. If such a function need return a
reference to a member of the object, it must return a const
reference, or use a const cast (or the member must be
mutable). That is:

struct Object
{
virtual Object*& at(int) = 0;
virtual const Object *const& at(long) const
{return other;} //Ok, other is const within const member
// function.

virtual Object *& wrong(long) const
{return other;} //Wrong, other is const within const member
// function, cannot be converted to Object*&.
private:
Object *other;
};


would it be that bad to
rephrase it into the form of the first method ?

Probably it would result in a compiler-error.
 

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
474,141
Messages
2,570,817
Members
47,365
Latest member
BurtonMeec

Latest Threads

Top