2

Using gcc version 4.8.2:

I'm running into an issue where the const qualifier on my parameters is disappearing when I compile my code. Here is an example:

main.cc:

#include <iostream>

class Base
{
        public:
        virtual int getSum( const int number ) = 0;
};

class Derived : public Base
{
        public:
        Derived( const int& num )
        : _myNumber( num )
        {}

        virtual int getSum( const int number )
        {
                return _myNumber + number;
        }

        private:
        int _myNumber;
};

int main( int argc, const char* argv[] )
{
        Base *b = new Derived( 2 );

        std::cout << b->getSum( 3 ) << "\n";

}

Compiled like so:

g++ main.cc -o const_test

When I run nm:

nm const_test | c++filt | grep getSum

I get the following output:

0000000000400b60 W Derived::getSum(int)

Why does the const disappear from my function when it compiles?

Kovaz
  • 127
  • 6

1 Answers1

4

Your function signature

virtual int getSum(const int number) = 0;

is actually exactly equivalent to

virtual int getSum(int number) = 0;

const has no effect on the function signature declaration for parameters passed by value.

The only effect is, that you can't change the parameter instance on the stack inside of a potential definition of this method. It's in fact sufficient to put it only there, to prevent changing the parameter's instance in the function body.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • It might be worth adding that what matters is the signature in the function definition. You mentioned the two signatures are identical, but sometimes people don't understand the implications of this. – juanchopanza Jun 18 '14 at 16:48
  • @juanchopanza THX for pointing out, I tried to clarify this a bit. – πάντα ῥεῖ Jun 18 '14 at 16:52