CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 4 1234 LastLast
Results 1 to 15 of 51
  1. #1
    Join Date
    Jul 2005
    Posts
    1,030

    A question regarding cast operator

    Here is the code,
    Code:
    class B
    {
    };
    
    class A
    {
    public:
    	operator B*()
    	{
    		B* pB = new B;
    		return pB;
    	}
    };
    
    
    
    int main()
    {
    	A a;
    
    	B* pB = (B*)a;  // #1
    	B* pB = static_cast<B*> (a);  // #2
    	return 0;
    }
    When I use cast operator defined in class A, should I use statement #1 or #2? BTW, they both compile. Thanks.

  2. #2
    Join Date
    Oct 2006
    Location
    Sweden
    Posts
    3,654

    Re: A question regarding cast operator

    I would say that in a C++ code you should never use a C-style cast and in a perfect world you shouldn't use cast as all...

    A C-style cast isn't as search friendly as a c++ cast i.e whenever you change stuff they still are there silenting the compiler.
    Debugging is twice as hard as writing the code in the first place.
    Therefore, if you write the code as cleverly as possible, you are, by
    definition, not smart enough to debug it.
    - Brian W. Kernighan

    To enhance your chance's of getting an answer be sure to read
    http://www.codeguru.com/forum/announ...nouncementid=6
    and http://www.codeguru.com/forum/showthread.php?t=366302 before posting

    Refresh your memory on formatting tags here
    http://www.codeguru.com/forum/misc.php?do=bbcode

    Get your free MS compiler here
    https://visualstudio.microsoft.com/vs

  3. #3
    Join Date
    Jul 2005
    Posts
    1,030

    Re: A question regarding cast operator

    Quote Originally Posted by S_M_A View Post
    I would say that in a C++ code you should never use a C-style cast and in a perfect world you shouldn't use cast as all...

    A C-style cast isn't as search friendly as a c++ cast i.e whenever you change stuff they still are there silenting the compiler.
    You are absolutely right. But my question is that is cast operator *() always equivalent to static_cast? Thanks.

  4. #4
    Join Date
    Jan 2009
    Posts
    1,689

    Re: A question regarding cast operator

    I'm pretty sure that both are required to work correctly according to the standard, but don't take my word on it. Someone more familiar with the standard, please verify. They both work for me, but that's no guarantee of the behavior with all compilers under all optimizations.

  5. #5
    Join Date
    May 2009
    Posts
    2,413

    Re: A question regarding cast operator

    Quote Originally Posted by LarryChen View Post
    When I use cast operator defined in class A, should I use statement #1 or #2? BTW, they both compile. Thanks.
    I've never found a reason to use the conversion operator so I may be wrong here but if you define a conversion operator why do you need to cast at all? Why don't you simply do,

    B* pB = a; // #3

    All of #1, #2 and #3 work but if you remove the conversion operator from A none of them will. That means they're all functionally equivalent in this case. They all simply invoke the conversion operator.

    Generally they're not equivalent though. When you cast explicitly you're recommended to use one of the "new" more targeted casts. In this case it would be static_cast.
    Last edited by nuzzle; June 2nd, 2012 at 12:43 AM.

  6. #6
    Join Date
    Jan 2009
    Posts
    1,689

    Re: A question regarding cast operator

    They aren't equivalent as far as I know.

    Code:
    B * pB = static_cast<B*>(a)
    means I want to treat it as B*, is that okay compiler?

    Code:
    B * pb = (B*)a
    means, screw what the compiler thinks, I'm casting it anyway.

    In fact, because a is not a pointer, I'm pretty sure if there wasn't an explicit cast operator, it would fail compilation (or at least warn.)



    Just FYI LarryChen, your code in the initial post leaks memory.

  7. #7
    Join Date
    May 2009
    Posts
    2,413

    Re: A question regarding cast operator

    ---

  8. #8
    Join Date
    Jan 2010
    Posts
    1,133

    Re: A question regarding cast operator

    Quote Originally Posted by ninja9578 View Post
    They aren't equivalent as far as I know.
    They aren't, but:

    Quote Originally Posted by ninja9578 View Post
    Code:
    B * pB = static_cast<B*>(a)
    means I want to treat it as B*, is that okay compiler?

    Code:
    B * pb = (B*)a
    means, screw what the compiler thinks, I'm casting it anyway.
    What do you mean?
    I thought c-style casts call C++-style casts in some order?

    @OP: BTW, although casts should generally be avoided, occasionally you do need to use them (for example, even if you can design your way out of it, the resulting code can end up being rather convoluted and even less performant, rendering the cast-based version both more elegant and more efficient).
    Also, here's a different view advocating against C++-style casts. IM(H)O, the guy has a point, and if you're gonna use C++-style casts, it should be for very specific reasons on very specific places.
    Of course, C++-style casts are considered a good C++ programming practice, so many people here will not agree.
    In the end, it's really up to you to learn more about both and form your own opinion.
    Last edited by TheGreatCthulhu; June 2nd, 2012 at 10:24 AM.

  9. #9
    Join Date
    Oct 2006
    Location
    Sweden
    Posts
    3,654

    Re: A question regarding cast operator

    He has some points for sure but for me the strongest argument for not using C-style casts is that they are more or less impossible to find without reading every single line of code.

    C++-style casts is easy to find, a search for _cast reveals them all to be thoroughly reviewed.
    Debugging is twice as hard as writing the code in the first place.
    Therefore, if you write the code as cleverly as possible, you are, by
    definition, not smart enough to debug it.
    - Brian W. Kernighan

    To enhance your chance's of getting an answer be sure to read
    http://www.codeguru.com/forum/announ...nouncementid=6
    and http://www.codeguru.com/forum/showthread.php?t=366302 before posting

    Refresh your memory on formatting tags here
    http://www.codeguru.com/forum/misc.php?do=bbcode

    Get your free MS compiler here
    https://visualstudio.microsoft.com/vs

  10. #10
    Join Date
    Oct 2008
    Posts
    1,456

    Re: A question regarding cast operator

    Quote Originally Posted by TheGreatCthulhu View Post
    I thought c-style casts call C++-style casts in some order?
    yes, but given that:

    1- how those c-casts are interpreted in terms of c++-casts depends on further rules usually ignored by c-cast users ( that is, if they knew them they probably knew how to use c++-casts and hence avoid c-casts in the first place )

    2- those rules are such as to give the more "relaxed" behavior

    hence it's fair to say that a c-cast "means, screw what the compiler thinks, I'm casting it anyway."

    Quote Originally Posted by TheGreatCthulhu View Post
    so many people here will not agree.
    I definitely disagree indeed !

    Quote Originally Posted by TheGreatCthulhu View Post
    IM(H)O, the guy has a point
    Quote Originally Posted by S_M_A
    He has some points for sure
    just for the sake of discussion, which are them ?

  11. #11
    Join Date
    Jan 2010
    Posts
    1,133

    Re: A question regarding cast operator

    @S_M_A:
    OK, that's true.
    If there's a need to search for C-style casts, one might use VS regular expressions in the find dialog, something along these lines: "=:b*\(.*\)".
    But, that might not find all the occurrences, and the fact that you need to come up with a cryptic regular expression makes the method error prone.

  12. #12
    Join Date
    Jan 2010
    Posts
    1,133

    Re: A question regarding cast operator

    Quote Originally Posted by superbonzo View Post
    just for the sake of discussion, which are them ?
    You didn't find it reasonable an assumption that they could be stated in the article?

    OK. According to Mr Kalev there:
    • C-style casts may perform more than one conversion at once - so what?
    • C-style casts make the code clearer.
    • Specialized cast operators are an example of over-engineering. [I'd like to add that's good if you have more tools in your toolbox, but that doesn't mean you should always use them.]
    • According to him static_cast isn't good for anything, and even Strosutrup discourages its use [although I'd say that that statement is possibly pulled out of context].
    • The code can compile without casting [as nuzzle pointed out].
      Quote Originally Posted by Danny Kalev
      Derived *p= pbase;
      int result= 12.56; //yes, this code compiles
      void*opaque =&myobj;
    • According to Kalev, C++ cast operators are dangerous [if I understood well, to novice programmers or to those who don't fully understand all the differences between various cast operators].
    • C-style casts are context-sensitive.
    • "ugly cast operators [don’t] dissuade them from using casts. [...] Programmers use casts not because they’re fun but because they are needed, or at least considered as needed."
    • Although C-style casts are harder to find, the argument is weakened by: (1) "many conversions in a C++ program are implicit, and don’t use any cast operator", and (2) you can use both C-style casts and C++-style casts in the same program. He also tried to make a point that you need to search for different cast operators, but as S_M_A noticed, one can just search for "_cast".
    Last edited by TheGreatCthulhu; June 2nd, 2012 at 11:30 AM.

  13. #13
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: A question regarding cast operator

    Quote Originally Posted by TheGreatCthulhu
    The code can compile without casting [as nuzzle pointed out].
    If the conversion function was declared as explicit then that would not be so.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  14. #14
    Join Date
    Oct 2008
    Posts
    1,456

    Re: A question regarding cast operator

    Quote Originally Posted by TheGreatCthulhu View Post
    You didn't find it reasonable an assumption that they could be stated in the article?
    yes I did; mine was a rhetoric question because I didn't actually find any; moreover, I know you like bullet lists ...

    Quote Originally Posted by TheGreatCthulhu View Post
    YAccording to Mr Kalev there:
    he's just combining obvious observations with unwarranted assumptions coming to debatable conclusions ...

    BTW, IMHO the only situation where c++ casts are unusable is with explicit arithmetic conversions; anyway, even then I always use the functional notation in this case; yes, it's functionally equivalent for non-class types, but it's more coherent ( the same syntax is used with objects of class types; also, consider generic code ) and less abuse-prone ( you need a typedef to perform complex pointer/reference conversions in functional notation ).

  15. #15
    Join Date
    Jan 2010
    Posts
    1,133

    Re: A question regarding cast operator

    @laserlight:
    (sorry for the slow reply, I went out in the meantime, so I'm typing this on my phone)

    Yes, but his (Kalev's) point was that there
    could be conversions in the code that aren't going to be found by the "_cast" search anyway.
    It all boils down to personal reasons/judgement, and how well the code is designed.
    Tell me: how many times will be significantly important to have control over the cast process? And I by that I mean that there's a strong reason to do so.
    Last edited by TheGreatCthulhu; June 2nd, 2012 at 12:26 PM.

Page 1 of 4 1234 LastLast

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured