StackStalk
  • Home
  • Java
    • Java Collection
    • Spring Boot Collection
  • Python
    • Python Collection
  • C++
    • C++ Collection
    • Progamming Problems
    • Algorithms
    • Data Structures
    • Design Patterns
  • General
    • Tips and Tricks

Tuesday, May 27, 2008

C++ Typecasting

 May 27, 2008     CPP     No comments   

What are the typecasting mechanisms in C++?

  • C++ provides a casting syntax with 4 reserved words, dynamic_cast, const_cast, static_cast and reinterpret_cast

What is dynamic_cast?

  • dynamic_cast is used to perform type conversions at run-time.
  • dynamic_cast operator can be used only on polymorphic classes. i.e. virtual functions are present.
  • On success the dynamic_cast returns a pointer to the object being converted.
  • On failure the dynamic_cast returns 0.

EXAMPLE: Demonstrate the basic usage of dynamic_cast

#include <iostream>
using namespace std;

class Base {  
  public:      
     virtual void print() {};
};

class Derived: public Base {};

void main(){
   Base* bPtr;
   Derived dObj;
   Derived* dPtr;

   bPtr = &dObj;

   if ( dPtr = dynamic_cast<Derived *>(bPtr) ) {
       cout << "Type is Derived" << endl;
   }
   else {
       cout << "Type is NOT Derived" << endl;
   }
}
OUTPUT:
Type is Derived

What is static_cast?

  • static_cast is used to perform type conversions that are well-defined.
  • static_cast doesn't perform any run-time checks.
  • static_cast is useful in scenarios where pointer to base class needs to be converted to a pointer to a derived class.

EXAMPLE: Demonstrate scenarios for usage of static_cast

#include <iostream>

using namespace std;

class Base {
};

class Derived: public Base {
};

void main()
{
   // static_cast for numeric conversions
   float a = 10/7;
   cout << a << endl;

   float b = static_cast<float>(10)/7;
   cout << b << endl;

   // static_cast for pointer conversions
   Base* bPtr;
   Derived dObj;
   Derived* dPtr;

   bPtr = &dObj;
   dPtr = static_cast<Derived*>(bPtr);
   bPtr = static_cast<Base*>(dPtr);
}
OUTPUT:
1
1.42857

What is const_cast?

  • const_cast is used when it is required to convert a const to a non-const.
  • This is also referred casting away constness

EXAMPLE: Demonstrate the usage of const_cast

#include <iostream>

using namespace std;

class MyClass {
      int data1;

   public:
      MyClass() { data1 = 100; }
      void Print() { cout << data1 << endl; }
};

void myfunc(MyClass* ptr)
{
   ptr->Print();
}

void main()
{
   const MyClass* ptr = new MyClass();

   /* Errors on call myfunc
      myfunc(ptr);
      Error E2034 dyncast.cpp 18: Cannot convert 'const MyClass *' to 'MyClass *' in function main()
      Error E2342 dyncast.cpp 18: Type mismatch in parameter 'ptr' (wanted 'MyClass *', got 'const MyClass *') in function main()
   */

   MyClass* ptr1 = const_cast<MyClass*>(ptr);
   myfunc(ptr1); // Ok

}
OUTPUT:
100

What is reinterpret_cast?

  • reinterpret_cast is used when it is required to assign one pointer type to another.
  • reinterpret_cast is the least safe and potential source of bugs.

EXAMPLE: Demonstrate the usage of reinterpret_cast

#include <iostream>
using namespace std;

void myfunc(void *arg)
{
   int val = reinterpret_cast<int>(arg);
   cout << val << endl;
}

void main()
{
   int a = 100;
   void* ptr = reinterpret_cast<void*>(a);
   myfunc(ptr);
}
OUTPUT:
100
  • Share This:  
Newer Post Older Post Home

0 comments:

Post a Comment

Follow @StackStalk
Get new posts by email:
Powered by follow.it

Popular Posts

  • Avro Producer and Consumer with Python using Confluent Kafka
    In this article, we will understand Avro a popular data serialization format in streaming data applications and develop a simple Avro Produc...
  • Monitor Spring Boot App with Micrometer and Prometheus
    Modern distributed applications typically have multiple microservices working together. Ability to monitor and manage aspects like health, m...
  • Server-Sent Events with Spring WebFlux
    In this article we will review the concepts of server-sent events and work on an example using WebFlux. Before getting into this article it ...
  • Implement caching in a Spring Boot microservice using Redis
    In this article we will explore how to use Redis as a data cache for a Spring Boot microservice using PostgreSQL as the database. Idea is to...
  • Python FastAPI microservice with Okta and OPA
    Authentication (AuthN) and Authorization (AuthZ) is a common challenge when developing microservices. In this article, we will explore how t...
  • Spring Boot with Okta and OPA
    Authentication (AuthN) and Authorization (AuthZ) is a common challenge when developing microservices. In this article, we will explore how t...
  • Getting started with Kafka in Python
    This article will provide an overview of Kafka and how to get started with Kafka in Python with a simple example. What is Kafka? ...
  • Getting started in GraphQL with Spring Boot
    In this article we will explore basic concepts on GraphQL and look at how to develop a microservice in Spring Boot with GraphQL support. ...

Copyright © StackStalk