+ Reply to Thread
Results 1 to 2 of 2

Thread: How to cast const to non const?

  1. #1

    How to cast const to non const?

    I am new to C++ programming.

    I have a const variable and want to cast it to non-const.

    How to cast const to non const?

    What is best way to do this?

    Please help.

  2. #2
    In below example, a function calls another function that takes a "const int" as an argument.

    The nConst variable is originally non-const.

    So it is safe to cast from "const int" to "non const int".

    Example:

    Code:
    void GiveMeConst(const int &nConst)
    {
    	int *nNonConst2 = const_cast<int *> (&nConst) ;
    
    	*nNonConst2 = 10 ;
    }
    
    void ConstConversion()
    {
    	int nConst = 42 ;
    
    	GiveMeConst(nConst) ;
    }
    Note:
    It is unsafe to cast from "Const int" to "non const int" if variable originally was "const"

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts