How to use "const". Part 2

How to use "const". Part 2

Continue the last document.

We will talk about how to use the “const” in a member function.

 

 

1. The “const” would be used when you gave some parameters to member function.

	class ClassA
{
public:
    ClassA(){}

    void Method1(const char* pcName)
    {
        char acModify_[10];
        ::memset(acModify_, 0, sizeof(acModify_));
        ::strcpy(acModify_, "change 1");
        
        //::strcpy(pcName, acModify_);
        
        ::printf("%s\n", pcName);
    }

    void Method2(const char* pcName)
    {
        char acModify_[10];
        ::memset(acModify_, 0, sizeof(acModify_));
        ::strcpy(acModify_, "change 2");
        
        pcName = acModify_;    
        
        ::printf("%s\n", pcName);
    }
};

Please be careful.

It would be fail when you removed the Method1’s mark.

But the Method2 would be success.

And the “const” would be modified when the application was being run.

If you need to avoid this question, you can refer the part 1.

 

 

2. The "const" was added in final of member funtion.

	class ClassB
{
public:
    ClassB():_iCount(0)    {}
    
    int Method1()const
    {
        //_iCount ++; // It wouldn't be compiled if you didn't mark this line.
        return _iCount;    
    }

    int Method2()
    {
        _iCount ++;
        return _iCount;    
    }

private:
    int _iCount;

};

It just could return a data without modify it if you add a "const" in final of member funtion.

 

 

3. The “const” was added in front of member funtion.

	class ClassC
{
public:
    ClassC()
    {
        ::memset(_acName, 0, sizeof(_acName));
        ::strcpy(_acName, "default");
    }
    
    const char* Method1()
    {
        return _acName;    
    }

private:
    char _acName[20];
};



int _tmain(int argc, _TCHAR* argv[])
{
    ClassC mClassC_;

    // There must be "const"
    const char* pcResult_  = mClassC_.Method1();
    
    ::printf("%s\n", pcResult_);
}