2

I am new to C++. A Beginner. While I was learning the casting feature provided by C++, was wondering why Casting feature specially static cast. When we know what type of variable would be required then why casting?.

Artem Koshelev
  • 10,548
  • 4
  • 36
  • 68
Lakshmi
  • 1,759
  • 4
  • 18
  • 23

4 Answers4

1

it's then you want to, for example, convert one type to another. say float to int. or object of different classes (usually base vs inherited). there's a lot of different examples. you will learn to use it mostly by solving some examples and other experience gaining stuff.

David
  • 3,190
  • 8
  • 25
  • 31
1

See When should static_cast, dynamic_cast and reinterpret_cast be used? for an explanation of the features of static_cast.

Community
  • 1
  • 1
Leonidas
  • 2,440
  • 15
  • 22
1

If I understand your question correctly, you are asking about why there is a static_cast operator in C++. Typecasting helps to move the pointer in a class hierarchy. And with static_cast you can downcast a pointer in the class hierarchial relationships. Though, such conversions aren't safe, you should be careful while dealing with it.

Mahesh
  • 34,573
  • 20
  • 89
  • 115
  • Mahesh, Trying to understand again here, considering the classes, static_cast is done only on pointers other than basic data types? – Lakshmi Feb 18 '11 at 06:57
  • Yes, converting a pointer to a base class to a pointer to a derived class. – Mahesh Feb 18 '11 at 07:06
  • She's asking if it's used **only** for pointers. The static_cast keyword can be used for any normal conversion between types. This includes any casts between numeric types, casts of pointers and references up the hierarchy, conversions with unary constructor, conversions with conversion operator. @Lakshmi, please learn to use google: http://www.cppreference.com/wiki/keywords/static_cast – Nav Feb 18 '11 at 07:55
  • For user defined types, I think, it is only for Pointers/References. Is my answer ambiguous? I guess, I answered accordingly to OP question. – Mahesh Feb 18 '11 at 08:01
1

static_cast is designed to reverse any implicit conversion. If You convert to void* implicitly, then you can convert back with static_cast if you know that you really are just reversing an earlier conversion.

ashmish2
  • 2,885
  • 8
  • 40
  • 54