Call a non-const member function from a const member function

后端 未结 7 1694
情深已故
情深已故 2020-12-29 06:15

I would like to know if its possible to call a non-const member function from a const member function. In the example below First gives a compiler error. I understand why it

7条回答
  •  甜味超标
    2020-12-29 06:54

    The restriction of const member methods are came from compile time. If you can fool the compiler, then yes.

    class CFoo
    { 
    public:
        CFoo() {m_Foo = this;}
        void tee();
    
        void bar() const 
        { 
            m_Foo->m_val++;  // fine 
            m_Foo->tee();    // fine
        }
    private:
       CFoo * m_Foo;
       int    m_Val;  
    
    };
    

    This actually abolishes the purpose of const member function, so it is better not to do it when design a new class. It is no harm to know that there is a way to do it,especially it can be used as an work-around on these old class that was not well designed on the concept of const member function.

提交回复
热议问题