You are here:

C++/overloading in C++

Advertisement


Question
Greetings, 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,

Answer
Well 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.

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Ralph McArdell

Expertise

I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.

Experience

My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at http://www.open-std.org/jtc1/sc22/wg21/.

Education/Credentials

©2016 About.com. All rights reserved.