Kiran's Blog

Ramblings from a dehydrated mind…

  • Archives

    • 14,897

const functions….

Posted by kiraninbng on July 25, 2006


If the function is declared as const,the compiler treats the “this” as const pointer.So if you are calling a non const member function of the same class then all you need to do is to remove the constantness of “this” pointer.The case for an embedded object of user defined type is pretty much straight forward.Below is an example,

Class CConstObj
{
 // dummy class
}

Class CConst
{
public:
    void Constfn()const;
    void NonConstfn(); 
    //…..
private:
    CConstObj m_oConstObj; 
 
}

void CConst::Constfn()const
{
    // Call a non const member function from the same class 
    ((CConstObj*)this)->NonConstfn();

    // Call non const member function of m_oConstObj ; 
    // m_oConstObj is a member of type CConstObj.
    ((CConstObj&)m_oConstObj).CallNonConstFn();
    ((CConstObj*)&m_oConstObj)->CallNonConstFn();
}

void CConst::NonConstfn()
{
   
}

Advertisements

3 Responses to “const functions….”

  1. FarPointer said

    Declaring a member function const also means you cant use that function to modify any class member variables.

    Note :- isn’t it a typo mismatch :-CTmDlg to CConst

  2. kiraninbng said

    Corrected the typo,thanks for pointing it out.

    The post basically talks about removing the constantness of the function,which means to modify member variables from a const function

  3. eti said

    Hi,

    Doing things like this is bad. A method declared const SHOULD not modify the object. It’s like a contract. If the instance of the class was located in read-only memory ( ex: on embeded devices ) the compiler will allow you to call a const method but at runtime BAD THINGS will happen. Also BAD THINGS can happen when a smart compiler optimizes the code assuming that a const method will not change the object.

    If you really need to modify a member variable in a const method declare the member mutable.

    In conclusion: Don’t go against the language, use it instead.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: