C++/overloading in C++
Expert: Ralph McArdell - 6/1/2011
QuestionGreetings, i have a question about operators overloading.
why do my parameters have to be constant in the function of the operator overloading ? ... and if i didn't use the const the compile gives me error.
Does all my parameters have to be constant or what exactly ?
Thanks,
AnswerWell I would expect whether you should specify a parameter as const or not depends on the specific situation.
In general you either pass parameters by value (for simple types such as integer types - as might be used as an index - e.g. for operator[] ) or by reference. If the parameter is not to be modified then it should be passed by reference to const otherwise it should not.
There are two reasons to pass by reference to const in cases that warrant it:
1/ It prevents accidental modification of parameters that should not be modified and indicates
this to the caller by the parameter being a reference to const.
2/ It allows const objects, const references to objects and temporary objects to be passed.
Consider this simple array of integers wrapper class:
#include <iostream>
#include <ostream>
#include <cstdlib>
class ArrayInt
{
int * the_ints;
size_t the_size;
void swap( ArrayInt & other )
{
int * tmp_ints ( this->the_ints );
size_t tmp_size( this->the_size );
this->the_ints = other.the_ints;
this->the_size = other.the_size;
other.the_ints = tmp_ints;
other.the_size = tmp_size;
}
public:
ArrayInt()
: the_ints(0)
, the_size(0)
{
}
ArrayInt( size_t size )
: the_ints(new int[size])
, the_size(size)
{
for ( size_t idx=0; idx!=the_size; ++idx )
{
this->the_ints[idx] = 0;
}
}
ArrayInt( ArrayInt const & other )
: the_ints(new int[other.the_size])
, the_size(other.the_size)
{
for ( size_t idx=0; idx!=the_size; ++idx )
{
this->the_ints[idx] = other.the_ints[idx];
}
}
~ArrayInt()
{
delete [] the_ints;
}
bool empty()
{
return the_size==0;
}
size_t size()
{
return the_size;
}
ArrayInt & operator=( ArrayInt const & rhs )
{
ArrayInt tmp(rhs);
this->swap(tmp);
return *this;
}
int & operator[](int index)
{
return the_ints[index];
}
int const & operator[](int index) const
{
return the_ints[index];
}
std::ostream & print( std::ostream & out ) const
{
for ( size_t idx=0; idx!=the_size; ++idx )
{
out << this->the_ints[idx] << ' ';
}
return out;
}
};
std::ostream & operator<<( std::ostream & out, ArrayInt const & v )
{
return v.print(out);
}
This provides a basic set of constructors, destructor and operators and operations. We can create empty arrays, arrays with a specific number of elements initially set to zero or a copy of an existing array. On going out of scope or when dynamically created ArrayInt objects are deleted the destructor deletes the contained int array.
We can check whether the array is empty or how many elements it has using the empty and size member function operations and print all elements values to a std::ostream object.
Note that no provision in this simple example has been made to allow additional elements to be added after construction but could be added (which might make the default constructor more useful!)
Provided operator overloads are:
- assignment: assigns the ArrayInt object on the left of = a copy of the ArrayInt object on the right hand side
(rhs). Obviously we would usually expect the right hand side object assigned from _not_ to be modified, and
as an array is probably expensive to copy we wish to pass by reference - hence we pass the right hand side
object as a reference to const ArrayInt. Note that this is _not_ an absolute requirement - see the standard
C++ library std::auto_pointer type template for an exception where the assigned from object is modified so
is passed by non-const reference.
- element access via []: here the elements are accessed by the unsigned integer type size_t, and so are passed
by value hence whether they are const or not is not of much relevance. Note however that a reference to the
element is returned. To cope with situations where we have a const ArrayInt object two overloads of
operator[] are provided - one that returns a non-const reference to the element and a const member function
overload that returns a reference to constant int element. Finally, no effort is made to range check the index
parameter values.
- output to stream using a non-member stream insertion operator function, operator<<: such operators take a
reference to the stream and a value to output. Again we would not expect outputting a value to modify
the value output and again ArrayInt objects may be expensive to copy so again we pass the value to output as
a reference to const ArrayInt. The std::ostream operator however may well be modified - data to write out and
stream state updates spring to mind, and streams cannot be copied so must be passed by reference - and as
they will be modified this should be by reference to non-const stream.
Here is a main program that shows some example uses of ArrayInt objects:
int main()
{
ArrayInt a(3);
a[0] = 0;
a[1] = 1;
a[2] = 2;
std::cout << "ArrayInt a contains: " << a << '\n';
std::cout << "Int a[1] has the value: " << a[1] << '\n';
ArrayInt const const_a(a);
std::cout << "ArrayInt const_a contains: " << const_a << '\n';
std::cout << "Int const_a[1] has the value: " << const_a[1] << '\n';
std::cout << "ArrayInt temporary copy of a contains: " << ArrayInt(a) << '\n';
std::cout << "Int (temporary copy of a)[1] has the value: " << ArrayInt(a)[1] << '\n';
}
You might like to try and:
- comment out the const operator[] member function
- make the v parameter to operator<< a reference to non-const
- make the out parameter to operator<< and ArrayInt::print a reference to const and make the
return type of these functions references to const also.
After each change try to build the program and see what errors you get, then reverse the changes, make sure the program builds and runs as before and go on to try the next variation.
As to exactly why you require a const parameter and the compiler complained - most likely because the argument you are passing is a const object, a const reference to an object or a temporary or literal value, however without more information I cannot be more specific or even comment on whether it is usual or required that the parameter for the operator overload function in question be a reference to a constant object.
Hope this helps a bit.