Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

kelaklub

Casting for class templates

This topic is 5230 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

If you have created a template class to represent say 2D points. This is just code I wrote on the fly so please excuse any typos.
template <typename tType>
class point2d
{
  public:
          tType x, y;
          
          // IS WRITING THE CONSTRUCTOR THIS WAY GOOD PRACTISE??

          point2d()
           {
             x = static_cast<tType>(0);
             y = static_cast<tType>(0);
           }
          
};
[edited by - kelaklub on February 26, 2004 3:00:22 PM]

Share this post


Link to post
Share on other sites
Advertisement
1) I don''t think a cast like this is necessary or makes too much sense, but I''d be interested to see some people''s opinions. The reason I say this is because it hides possible problems you might have if someone designed a point2d with a class that does not correctly convert from an int/float to a value of its type.


// does not provide a means (implicit or otherwise) of

// casting to an int, stupid but it COULD happen

class MyHugeInt {
char* pByteArray;
public:
MyHugeInt() { pByteArray = new char[255]; }
~MyHugeInt() { delete[] pByteArray; }
};

static_cast<MyHugeInt>(0); // does this make sense?



Now the cast to MyHugeInt on 0 make any sense? Doesn''t it cause undefined behavior?

2) get in the habit of using initializer lists:


point2d() : x(static_cast<tType>(0), y(static_cast<tType>(0))
{ }


Regards,
Jeff


[ CodeDread ]

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!