C++ Memory::const_pointer_cast



C++ Memory::const_pointer_cast kind of casting alters the consistency of the object being pointed at by the pointer, either to set it or to remove it. A const pointer can be passed to a function that requires a non-const parameter, for instance.

Const_cast method is used to add or remove const to a variable and it is the legal way to remove constness from a variable. Const_cast converts a null pointer value to the destination type of null pointer value.

Syntax

Following is the syntax for C++ Memory::const_pointer_cast −

shared_ptr<T> const_pointer_cast (const shared_ptr<U>& sp) noexcept;

Parameters

sp − Its a shared pointer.

Example 1

Let's look into the following example, where we are going to perform cast_pointer_casting and getting the output.

#include <iostream>
#include <memory>
int main (){
   std::shared_ptr<int> x;
   std::shared_ptr<const int> y;
   x = std::make_shared<int>(12);
   y = std::const_pointer_cast<const int>(x);
   std::cout << "*Result: " << *y << '\n';
   *x = 23;
   std::cout << "*Result: " << *y << '\n';
   return 0;
}

Output

Let us compile and run the above program, this will produce the following result −

*Result: 12
*Result: 23

Example 2

Following is the another example, where the going to use the const_cast and retriveing the output.

#include <iostream>
using namespace std;
void print (char * str){
   cout << str << '\n';
}
int main (){
   const char * c = "Hello World";
   print ( const_cast<char *> (c) );
   return 0;
}

Output

On running the above code, it will display the output as shown below −

Hello World

Example 3

Considering the another scenario, where we are going to use the const_cast and retriveing the output.

#include <iostream>
using namespace std;
class A{
   public:
      void setNumber( int );
      void printNumber() const;
   private:
      int number;
};
void A::setNumber( int num ){
   number = num;
}
void A::printNumber() const{
   cout << "\nBefore: " << number;
   const_cast< A * >( this )->number--;
   cout << "\nAfter: " << number;
}
int main(){
   A X;
   X.setNumber( 10 );
   X.printNumber();
}

Output

when the code gets executed, it will generate the output as shown below −

Before: 10
After: 9
Advertisements