const qualifier disappears from pure virtual funct

2020-04-12 16:27发布

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?

1条回答
放荡不羁爱自由
2楼-- · 2020-04-12 16:54

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.

查看更多
登录 后发表回答