const qualifier disappears from pure virtual function [duplicate]

僤鯓⒐⒋嵵緔 提交于 2019-12-20 03:17:31

问题


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:


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.



来源:https://stackoverflow.com/questions/24290732/const-qualifier-disappears-from-pure-virtual-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!