Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Intermediate
Oct 29, 2007

Overloading the const and non-const Member Functions

We all know about the function overloading feature in C++, which allows us to have the same name given for a function with different signatures (here, different signature means different types or number of arguments for that function). But what about overloading based on the const-ness of a member function? Take the following function:

    class MyArray
    {
    private:
        int m_iInts[100];  // Array of integers

    public:
        int& operator [](int iIndex);  // Overloading subscript operator
    };

    int& MyArray::operator[](int iIndex) // Definition
    {
        return m_iInts[iIndex];
    }
You are trying to create an integer array class, with an overloaded operator function for the subscript access of the array. You should be able to say:

    MyArray objArray;
    objArray[10] = 100;
This establishes a call to the operator[](int) member function, which returns a reference to the requested array member. It also assigns a value to that particular array member. However, consider the situation below:

    void PrintArray(const MyArray &obj)
    {
        // Code for printing the elements
        cout<<obj[10]<<endl;
    }
Assuming that this is a function for printing the array elements, this takes a constant reference to MyArray instance as a parameter. Here's the problem: when you try to print the value by saying obj[10], you won't be able to access the non-const version of operator[](int), because the object is of constant type. The compiler will complain about this, saying:

    no operator defined which takes a left-hand operand of type 'const class MyArray'
In this situation, you need to declare another version of operator[](int), specifically for const objects:

    const int MyArray::operator[](int index) const
    {
        return m_iElements[index];
    } 
This is a const member function, meaning not supposed to change the value of any member variable. Hence, you have two versions of member functions with the same name and even the same argument, but different in const-ness.

    int& operator [](int iIndex);                 // non-const version
    const int operator[](int index) const;    // const version 
The first version should be be used for all non-const objects, and the latter only used for const objects.

Prashanth Narayanaswamy
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap