Why does static_cast allow downcasts when logically it should refuse them for safety purposes or static_cast is not about safety?Does the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function?Should I use static_cast or reinterpret_cast when casting a void* to whateverWhen should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?The meaning of static in C++Pretty-print C++ STL containersRetrieving pointers from a vectorAre there cases where downcasting an actual Base to a Derived would be defined?Error C2679: “binary '<<': no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion)”C++ Compiler doesn't recognize templated diamondWhy is the downcast in CRTP defined behaviour
How would you say “AKA/as in”?
What risks are there when you clear your cookies instead of logging off?
Word for a small burst of laughter that can't be held back
Their answer is discrete, mine is continuous. They baited me into the wrong answer. I have a P Exam question
How were concentration and extermination camp guards recruited?
What happened to all the nuclear material being smuggled after the fall of the USSR?
Finding the constrain of integral
What's the correct term for a waitress in the Middle Ages?
Why does the Schrödinger equation work so well for the Hydrogen atom despite the relativistic boundary at the nucleus?
Movie where a boy is transported into the future by an alien spaceship
You've spoiled/damaged the card
How to make thick Asian sauces?
Sharing one invocation list between multiple events on the same object in C#
Why don't B747s start takeoffs with full throttle?
Building a road to escape Earth's gravity by making a pyramid on Antartica
Is the decompression of compressed and encrypted data without decryption also theoretically impossible?
How do I calculate APR from monthly instalments?
PhD student with mental health issues and bad performance
How can Iron Man's suit withstand this?
Company did not petition for visa in a timely manner. Is asking me to work from overseas, but wants me to take a paycut
Why don’t airliners have temporary liveries?
Pronoun introduced before its antecedent
Why did Hela need Heimdal's sword?
Function to extract float from different price patterns
Why does static_cast allow downcasts when logically it should refuse them for safety purposes or static_cast is not about safety?
Does the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function?Should I use static_cast or reinterpret_cast when casting a void* to whateverWhen should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?The meaning of static in C++Pretty-print C++ STL containersRetrieving pointers from a vectorAre there cases where downcasting an actual Base to a Derived would be defined?Error C2679: “binary '<<': no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion)”C++ Compiler doesn't recognize templated diamondWhy is the downcast in CRTP defined behaviour
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
In the following example the compiler accepts the static_cast
downcast resulting in undefined behavior while I thought static_cast
was all about safety (that C-style casts were unable to provide).
#include <iostream>
class Base
public:
int x = 10;
;
class Derived1: public Base
public:
int y = 20;
;
class Derived2 : public Base
public:
int z = 30;
int w = 40;
;
int main()
Derived1 d1;
Base* bp1 = static_cast<Base*>(&d1);
Derived2* dp1 = static_cast<Derived2*>(bp1);
std::cout << dp1->z << std::endl; // outputs 20
std::cout << dp1->w << std::endl; // outputs random value
c++
|
show 1 more comment
In the following example the compiler accepts the static_cast
downcast resulting in undefined behavior while I thought static_cast
was all about safety (that C-style casts were unable to provide).
#include <iostream>
class Base
public:
int x = 10;
;
class Derived1: public Base
public:
int y = 20;
;
class Derived2 : public Base
public:
int z = 30;
int w = 40;
;
int main()
Derived1 d1;
Base* bp1 = static_cast<Base*>(&d1);
Derived2* dp1 = static_cast<Derived2*>(bp1);
std::cout << dp1->z << std::endl; // outputs 20
std::cout << dp1->w << std::endl; // outputs random value
c++
7
I don't think anybody ever pretended that C++ is a safe language.
– StoryTeller
Mar 24 at 14:41
1
Nope, for downcasting with safety you needdynamic_cast
(and null checks) -static_cast
tells the compiler you are 100% sure you have the right type
– UnholySheep
Mar 24 at 14:41
1
Upcast is performed implicitly, no special syntax required. The point ofstatic_cast
is largely to be able to explicitly perform the reverse of implicit conversions. It is generally impossible to verify at compile time that such a conversion is valid - if it were, the compiler would allow it implicitly.
– Igor Tandetnik
Mar 24 at 14:41
1
static_cast
is "safe" in the sense that it doesn't let you convert between unrelated types. The safety goal of C++ is pretty much to not be quite as unsafe as C.
– molbdnilo
Mar 24 at 14:51
1
static_cast
provides all of the safety that can be provided at zero cost.dynamic_cast
provides more safety but it comes with a cost attached.
– Oktalist
Mar 24 at 15:01
|
show 1 more comment
In the following example the compiler accepts the static_cast
downcast resulting in undefined behavior while I thought static_cast
was all about safety (that C-style casts were unable to provide).
#include <iostream>
class Base
public:
int x = 10;
;
class Derived1: public Base
public:
int y = 20;
;
class Derived2 : public Base
public:
int z = 30;
int w = 40;
;
int main()
Derived1 d1;
Base* bp1 = static_cast<Base*>(&d1);
Derived2* dp1 = static_cast<Derived2*>(bp1);
std::cout << dp1->z << std::endl; // outputs 20
std::cout << dp1->w << std::endl; // outputs random value
c++
In the following example the compiler accepts the static_cast
downcast resulting in undefined behavior while I thought static_cast
was all about safety (that C-style casts were unable to provide).
#include <iostream>
class Base
public:
int x = 10;
;
class Derived1: public Base
public:
int y = 20;
;
class Derived2 : public Base
public:
int z = 30;
int w = 40;
;
int main()
Derived1 d1;
Base* bp1 = static_cast<Base*>(&d1);
Derived2* dp1 = static_cast<Derived2*>(bp1);
std::cout << dp1->z << std::endl; // outputs 20
std::cout << dp1->w << std::endl; // outputs random value
c++
c++
edited Mar 24 at 20:10
Boann
38k1291123
38k1291123
asked Mar 24 at 14:39
Soulimane MammarSoulimane Mammar
572414
572414
7
I don't think anybody ever pretended that C++ is a safe language.
– StoryTeller
Mar 24 at 14:41
1
Nope, for downcasting with safety you needdynamic_cast
(and null checks) -static_cast
tells the compiler you are 100% sure you have the right type
– UnholySheep
Mar 24 at 14:41
1
Upcast is performed implicitly, no special syntax required. The point ofstatic_cast
is largely to be able to explicitly perform the reverse of implicit conversions. It is generally impossible to verify at compile time that such a conversion is valid - if it were, the compiler would allow it implicitly.
– Igor Tandetnik
Mar 24 at 14:41
1
static_cast
is "safe" in the sense that it doesn't let you convert between unrelated types. The safety goal of C++ is pretty much to not be quite as unsafe as C.
– molbdnilo
Mar 24 at 14:51
1
static_cast
provides all of the safety that can be provided at zero cost.dynamic_cast
provides more safety but it comes with a cost attached.
– Oktalist
Mar 24 at 15:01
|
show 1 more comment
7
I don't think anybody ever pretended that C++ is a safe language.
– StoryTeller
Mar 24 at 14:41
1
Nope, for downcasting with safety you needdynamic_cast
(and null checks) -static_cast
tells the compiler you are 100% sure you have the right type
– UnholySheep
Mar 24 at 14:41
1
Upcast is performed implicitly, no special syntax required. The point ofstatic_cast
is largely to be able to explicitly perform the reverse of implicit conversions. It is generally impossible to verify at compile time that such a conversion is valid - if it were, the compiler would allow it implicitly.
– Igor Tandetnik
Mar 24 at 14:41
1
static_cast
is "safe" in the sense that it doesn't let you convert between unrelated types. The safety goal of C++ is pretty much to not be quite as unsafe as C.
– molbdnilo
Mar 24 at 14:51
1
static_cast
provides all of the safety that can be provided at zero cost.dynamic_cast
provides more safety but it comes with a cost attached.
– Oktalist
Mar 24 at 15:01
7
7
I don't think anybody ever pretended that C++ is a safe language.
– StoryTeller
Mar 24 at 14:41
I don't think anybody ever pretended that C++ is a safe language.
– StoryTeller
Mar 24 at 14:41
1
1
Nope, for downcasting with safety you need
dynamic_cast
(and null checks) - static_cast
tells the compiler you are 100% sure you have the right type– UnholySheep
Mar 24 at 14:41
Nope, for downcasting with safety you need
dynamic_cast
(and null checks) - static_cast
tells the compiler you are 100% sure you have the right type– UnholySheep
Mar 24 at 14:41
1
1
Upcast is performed implicitly, no special syntax required. The point of
static_cast
is largely to be able to explicitly perform the reverse of implicit conversions. It is generally impossible to verify at compile time that such a conversion is valid - if it were, the compiler would allow it implicitly.– Igor Tandetnik
Mar 24 at 14:41
Upcast is performed implicitly, no special syntax required. The point of
static_cast
is largely to be able to explicitly perform the reverse of implicit conversions. It is generally impossible to verify at compile time that such a conversion is valid - if it were, the compiler would allow it implicitly.– Igor Tandetnik
Mar 24 at 14:41
1
1
static_cast
is "safe" in the sense that it doesn't let you convert between unrelated types. The safety goal of C++ is pretty much to not be quite as unsafe as C.– molbdnilo
Mar 24 at 14:51
static_cast
is "safe" in the sense that it doesn't let you convert between unrelated types. The safety goal of C++ is pretty much to not be quite as unsafe as C.– molbdnilo
Mar 24 at 14:51
1
1
static_cast
provides all of the safety that can be provided at zero cost. dynamic_cast
provides more safety but it comes with a cost attached.– Oktalist
Mar 24 at 15:01
static_cast
provides all of the safety that can be provided at zero cost. dynamic_cast
provides more safety but it comes with a cost attached.– Oktalist
Mar 24 at 15:01
|
show 1 more comment
3 Answers
3
active
oldest
votes
I thought
static_cast
was all about safety (that C style cast were unable to provide)
static_cast
is safer than a C-style cast. But not because it's impossible to go wrong with it. It's safer because it's only less likely to go wrong. When we write a C-style cast, a compiler will go through this list to appease us:
When the C-style cast expression is encountered, the compiler attempts
to interpret it as the following cast expressions, in this order:
const_cast<new_type>(expression)
;
static_cast<new_type>(expression)
, with extensions: pointer or reference to a derived class is additionally allowed to be cast to pointer or reference to unambiguous base class (and vice versa) even if the base class is inaccessible (that is, this cast ignores the private inheritance specifier). Same applies to casting pointer to member to pointer to member of unambiguous non-virtual base;
static_cast
(with extensions) followed byconst_cast
;
reinterpret_cast<new_type>(expression)
;
reinterpret_cast
followed byconst_cast
.
The first choice that satisfies the requirements of the respective
cast operator is selected, even if it cannot be compiled (see
example). If the cast can be interpreted in more than one way as
static_cast
followed by aconst_cast
, it cannot be compiled. In
addition, C-style cast notation is allowed to cast from, to, and
between pointers to incomplete class type. If both expression and
new_type are pointers to incomplete class types, it's unspecified
whetherstatic_cast
orreinterpret_cast
gets selected.
The point in favoring static_cast
to that, is that you have a finer grained control over the resulting cast, which does grant a measure of added safety. But it doesn't change the fact that the C++ object model requires that static_cast
support casting even when undefined behavior is possible. Only dynamic_cast
(not on the above list, by the way) has an added bit of safety for polymorphic types, but that's not without overhead.
add a comment |
You use dynamic_cast
only really when you are not sure if the cast is going to succeed and you catch exceptions or check for nullptr. However if you are sure your downcasting is going to succeed, the language allows you to use static_cast
. If you were wrong, that is your problem. In an ideal world every cast would succeed in 100% of the time. But we don't live in an ideal world. It's a bit like array subscript. arr[5]
means "I am absolutely sure this array has at least 6 elements. Compiler doesn't need to check". If your array was smaller than you expected, that's again your problem.
add a comment |
I don't really know what to tell you. Why does it allow such a cast? For when you need/want one.
Don't want to use it? Don't! You could switch to dynamic_cast
(more expensive), or don't cast.
C++ lets you do plenty of things that require thought and care. This is one of them.
But it is still safer than C. The static_cast
won't let you cast bp1
to an UrgleBurgle*
, for example.
Of course ultimately you can still use the C-style casts if you like. I mean, I wouldn't advise it, but you could. C++ is all about choice (usually between a terrible option and a slightly less terrible option).
4
I love C++'s "You only pay for what you use" system!
– Ayxan
Mar 24 at 14:58
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55324915%2fwhy-does-static-cast-allow-downcasts-when-logically-it-should-refuse-them-for-sa%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
I thought
static_cast
was all about safety (that C style cast were unable to provide)
static_cast
is safer than a C-style cast. But not because it's impossible to go wrong with it. It's safer because it's only less likely to go wrong. When we write a C-style cast, a compiler will go through this list to appease us:
When the C-style cast expression is encountered, the compiler attempts
to interpret it as the following cast expressions, in this order:
const_cast<new_type>(expression)
;
static_cast<new_type>(expression)
, with extensions: pointer or reference to a derived class is additionally allowed to be cast to pointer or reference to unambiguous base class (and vice versa) even if the base class is inaccessible (that is, this cast ignores the private inheritance specifier). Same applies to casting pointer to member to pointer to member of unambiguous non-virtual base;
static_cast
(with extensions) followed byconst_cast
;
reinterpret_cast<new_type>(expression)
;
reinterpret_cast
followed byconst_cast
.
The first choice that satisfies the requirements of the respective
cast operator is selected, even if it cannot be compiled (see
example). If the cast can be interpreted in more than one way as
static_cast
followed by aconst_cast
, it cannot be compiled. In
addition, C-style cast notation is allowed to cast from, to, and
between pointers to incomplete class type. If both expression and
new_type are pointers to incomplete class types, it's unspecified
whetherstatic_cast
orreinterpret_cast
gets selected.
The point in favoring static_cast
to that, is that you have a finer grained control over the resulting cast, which does grant a measure of added safety. But it doesn't change the fact that the C++ object model requires that static_cast
support casting even when undefined behavior is possible. Only dynamic_cast
(not on the above list, by the way) has an added bit of safety for polymorphic types, but that's not without overhead.
add a comment |
I thought
static_cast
was all about safety (that C style cast were unable to provide)
static_cast
is safer than a C-style cast. But not because it's impossible to go wrong with it. It's safer because it's only less likely to go wrong. When we write a C-style cast, a compiler will go through this list to appease us:
When the C-style cast expression is encountered, the compiler attempts
to interpret it as the following cast expressions, in this order:
const_cast<new_type>(expression)
;
static_cast<new_type>(expression)
, with extensions: pointer or reference to a derived class is additionally allowed to be cast to pointer or reference to unambiguous base class (and vice versa) even if the base class is inaccessible (that is, this cast ignores the private inheritance specifier). Same applies to casting pointer to member to pointer to member of unambiguous non-virtual base;
static_cast
(with extensions) followed byconst_cast
;
reinterpret_cast<new_type>(expression)
;
reinterpret_cast
followed byconst_cast
.
The first choice that satisfies the requirements of the respective
cast operator is selected, even if it cannot be compiled (see
example). If the cast can be interpreted in more than one way as
static_cast
followed by aconst_cast
, it cannot be compiled. In
addition, C-style cast notation is allowed to cast from, to, and
between pointers to incomplete class type. If both expression and
new_type are pointers to incomplete class types, it's unspecified
whetherstatic_cast
orreinterpret_cast
gets selected.
The point in favoring static_cast
to that, is that you have a finer grained control over the resulting cast, which does grant a measure of added safety. But it doesn't change the fact that the C++ object model requires that static_cast
support casting even when undefined behavior is possible. Only dynamic_cast
(not on the above list, by the way) has an added bit of safety for polymorphic types, but that's not without overhead.
add a comment |
I thought
static_cast
was all about safety (that C style cast were unable to provide)
static_cast
is safer than a C-style cast. But not because it's impossible to go wrong with it. It's safer because it's only less likely to go wrong. When we write a C-style cast, a compiler will go through this list to appease us:
When the C-style cast expression is encountered, the compiler attempts
to interpret it as the following cast expressions, in this order:
const_cast<new_type>(expression)
;
static_cast<new_type>(expression)
, with extensions: pointer or reference to a derived class is additionally allowed to be cast to pointer or reference to unambiguous base class (and vice versa) even if the base class is inaccessible (that is, this cast ignores the private inheritance specifier). Same applies to casting pointer to member to pointer to member of unambiguous non-virtual base;
static_cast
(with extensions) followed byconst_cast
;
reinterpret_cast<new_type>(expression)
;
reinterpret_cast
followed byconst_cast
.
The first choice that satisfies the requirements of the respective
cast operator is selected, even if it cannot be compiled (see
example). If the cast can be interpreted in more than one way as
static_cast
followed by aconst_cast
, it cannot be compiled. In
addition, C-style cast notation is allowed to cast from, to, and
between pointers to incomplete class type. If both expression and
new_type are pointers to incomplete class types, it's unspecified
whetherstatic_cast
orreinterpret_cast
gets selected.
The point in favoring static_cast
to that, is that you have a finer grained control over the resulting cast, which does grant a measure of added safety. But it doesn't change the fact that the C++ object model requires that static_cast
support casting even when undefined behavior is possible. Only dynamic_cast
(not on the above list, by the way) has an added bit of safety for polymorphic types, but that's not without overhead.
I thought
static_cast
was all about safety (that C style cast were unable to provide)
static_cast
is safer than a C-style cast. But not because it's impossible to go wrong with it. It's safer because it's only less likely to go wrong. When we write a C-style cast, a compiler will go through this list to appease us:
When the C-style cast expression is encountered, the compiler attempts
to interpret it as the following cast expressions, in this order:
const_cast<new_type>(expression)
;
static_cast<new_type>(expression)
, with extensions: pointer or reference to a derived class is additionally allowed to be cast to pointer or reference to unambiguous base class (and vice versa) even if the base class is inaccessible (that is, this cast ignores the private inheritance specifier). Same applies to casting pointer to member to pointer to member of unambiguous non-virtual base;
static_cast
(with extensions) followed byconst_cast
;
reinterpret_cast<new_type>(expression)
;
reinterpret_cast
followed byconst_cast
.
The first choice that satisfies the requirements of the respective
cast operator is selected, even if it cannot be compiled (see
example). If the cast can be interpreted in more than one way as
static_cast
followed by aconst_cast
, it cannot be compiled. In
addition, C-style cast notation is allowed to cast from, to, and
between pointers to incomplete class type. If both expression and
new_type are pointers to incomplete class types, it's unspecified
whetherstatic_cast
orreinterpret_cast
gets selected.
The point in favoring static_cast
to that, is that you have a finer grained control over the resulting cast, which does grant a measure of added safety. But it doesn't change the fact that the C++ object model requires that static_cast
support casting even when undefined behavior is possible. Only dynamic_cast
(not on the above list, by the way) has an added bit of safety for polymorphic types, but that's not without overhead.
answered Mar 24 at 15:03
StoryTellerStoryTeller
110k16235297
110k16235297
add a comment |
add a comment |
You use dynamic_cast
only really when you are not sure if the cast is going to succeed and you catch exceptions or check for nullptr. However if you are sure your downcasting is going to succeed, the language allows you to use static_cast
. If you were wrong, that is your problem. In an ideal world every cast would succeed in 100% of the time. But we don't live in an ideal world. It's a bit like array subscript. arr[5]
means "I am absolutely sure this array has at least 6 elements. Compiler doesn't need to check". If your array was smaller than you expected, that's again your problem.
add a comment |
You use dynamic_cast
only really when you are not sure if the cast is going to succeed and you catch exceptions or check for nullptr. However if you are sure your downcasting is going to succeed, the language allows you to use static_cast
. If you were wrong, that is your problem. In an ideal world every cast would succeed in 100% of the time. But we don't live in an ideal world. It's a bit like array subscript. arr[5]
means "I am absolutely sure this array has at least 6 elements. Compiler doesn't need to check". If your array was smaller than you expected, that's again your problem.
add a comment |
You use dynamic_cast
only really when you are not sure if the cast is going to succeed and you catch exceptions or check for nullptr. However if you are sure your downcasting is going to succeed, the language allows you to use static_cast
. If you were wrong, that is your problem. In an ideal world every cast would succeed in 100% of the time. But we don't live in an ideal world. It's a bit like array subscript. arr[5]
means "I am absolutely sure this array has at least 6 elements. Compiler doesn't need to check". If your array was smaller than you expected, that's again your problem.
You use dynamic_cast
only really when you are not sure if the cast is going to succeed and you catch exceptions or check for nullptr. However if you are sure your downcasting is going to succeed, the language allows you to use static_cast
. If you were wrong, that is your problem. In an ideal world every cast would succeed in 100% of the time. But we don't live in an ideal world. It's a bit like array subscript. arr[5]
means "I am absolutely sure this array has at least 6 elements. Compiler doesn't need to check". If your array was smaller than you expected, that's again your problem.
edited Mar 24 at 14:54
answered Mar 24 at 14:49
AyxanAyxan
3,174725
3,174725
add a comment |
add a comment |
I don't really know what to tell you. Why does it allow such a cast? For when you need/want one.
Don't want to use it? Don't! You could switch to dynamic_cast
(more expensive), or don't cast.
C++ lets you do plenty of things that require thought and care. This is one of them.
But it is still safer than C. The static_cast
won't let you cast bp1
to an UrgleBurgle*
, for example.
Of course ultimately you can still use the C-style casts if you like. I mean, I wouldn't advise it, but you could. C++ is all about choice (usually between a terrible option and a slightly less terrible option).
4
I love C++'s "You only pay for what you use" system!
– Ayxan
Mar 24 at 14:58
add a comment |
I don't really know what to tell you. Why does it allow such a cast? For when you need/want one.
Don't want to use it? Don't! You could switch to dynamic_cast
(more expensive), or don't cast.
C++ lets you do plenty of things that require thought and care. This is one of them.
But it is still safer than C. The static_cast
won't let you cast bp1
to an UrgleBurgle*
, for example.
Of course ultimately you can still use the C-style casts if you like. I mean, I wouldn't advise it, but you could. C++ is all about choice (usually between a terrible option and a slightly less terrible option).
4
I love C++'s "You only pay for what you use" system!
– Ayxan
Mar 24 at 14:58
add a comment |
I don't really know what to tell you. Why does it allow such a cast? For when you need/want one.
Don't want to use it? Don't! You could switch to dynamic_cast
(more expensive), or don't cast.
C++ lets you do plenty of things that require thought and care. This is one of them.
But it is still safer than C. The static_cast
won't let you cast bp1
to an UrgleBurgle*
, for example.
Of course ultimately you can still use the C-style casts if you like. I mean, I wouldn't advise it, but you could. C++ is all about choice (usually between a terrible option and a slightly less terrible option).
I don't really know what to tell you. Why does it allow such a cast? For when you need/want one.
Don't want to use it? Don't! You could switch to dynamic_cast
(more expensive), or don't cast.
C++ lets you do plenty of things that require thought and care. This is one of them.
But it is still safer than C. The static_cast
won't let you cast bp1
to an UrgleBurgle*
, for example.
Of course ultimately you can still use the C-style casts if you like. I mean, I wouldn't advise it, but you could. C++ is all about choice (usually between a terrible option and a slightly less terrible option).
edited Mar 24 at 15:02
answered Mar 24 at 14:56
Lightness Races in OrbitLightness Races in Orbit
301k56488840
301k56488840
4
I love C++'s "You only pay for what you use" system!
– Ayxan
Mar 24 at 14:58
add a comment |
4
I love C++'s "You only pay for what you use" system!
– Ayxan
Mar 24 at 14:58
4
4
I love C++'s "You only pay for what you use" system!
– Ayxan
Mar 24 at 14:58
I love C++'s "You only pay for what you use" system!
– Ayxan
Mar 24 at 14:58
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55324915%2fwhy-does-static-cast-allow-downcasts-when-logically-it-should-refuse-them-for-sa%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
7
I don't think anybody ever pretended that C++ is a safe language.
– StoryTeller
Mar 24 at 14:41
1
Nope, for downcasting with safety you need
dynamic_cast
(and null checks) -static_cast
tells the compiler you are 100% sure you have the right type– UnholySheep
Mar 24 at 14:41
1
Upcast is performed implicitly, no special syntax required. The point of
static_cast
is largely to be able to explicitly perform the reverse of implicit conversions. It is generally impossible to verify at compile time that such a conversion is valid - if it were, the compiler would allow it implicitly.– Igor Tandetnik
Mar 24 at 14:41
1
static_cast
is "safe" in the sense that it doesn't let you convert between unrelated types. The safety goal of C++ is pretty much to not be quite as unsafe as C.– molbdnilo
Mar 24 at 14:51
1
static_cast
provides all of the safety that can be provided at zero cost.dynamic_cast
provides more safety but it comes with a cost attached.– Oktalist
Mar 24 at 15:01