2

From http://www.stroustrup.com/bs_faq.html#improve-my-C++-programs

Q: What's the best way to improve my C++ programs?

A: I couldn't say. That depends on how you use it. Most people underestimate abstract classes and templates. Conversely, most people seriously overuse casts and macros.

I've seen the sentiment about macros before, but what do "most people" do with casts when they could be doing something else? I'm thinking pointer casts.

Community
  • 1
  • 1
leewz
  • 3,201
  • 1
  • 18
  • 38
  • My best guess here is that both parts of that answer go hand in hand. People underestimate abstract classes and templates in respect to dynamic binding. That leads to unnecessary casts and use of macros where better OO design, speak extensively using polymorphism in this case, could be used instead. – SBI Dec 06 '13 at 16:14
  • Given that there's a question a few further down, "When will we have a C++ standard?", that text may well have been written over 15 years ago. If so, it may not have been updated since (although many of the FAQs have been updated more recently, of course). I really wouldn't worry about what "most people" did. – Steve Jessop Dec 06 '13 at 18:05
  • @SteveJessop The question, yes, but the answer to it is updated. – leewz Dec 06 '13 at 19:04

2 Answers2

3

what do "most people" do with casts when they could be doing something else?

Your guess on pointer casts sound about right.

Consider this code:

class some_base { /* ... */ };

class some_implementation: public some_base
{ void do_impl_stuff() { /* ... */ } }; // do_impl code is in specialization

bad client code:

void do_stuff(some_base* base)
{
    if(some_implementation* p = dynamic_cast<some_implementation*>(base)) {
        p->do_impl_stuff();
    }
}

better alternative:

class some_base
{
public:
    virtual void do_impl_stuff() = 0;
    virtual ~some_base() = default;
};

class some_implementation: public some_base
{ virtual void do_impl_stuff() override { /* ... */ } };

void do_stuff(some_base* base)
{
    base->do_impl_stuff();
}

The first example "abuses" the dynamic cast. The second, is "doing something else"

Edit: The point Xephon is making is also valid.

Regarding overuse of macros, most code you write using macros in C++ can (and generally speaking should) be written using templated code.

For an example, look at the C #define min/#define max vs. the C++ std::min and std::max (the C version has so many problems it's not even funny).

utnapistim
  • 26,809
  • 3
  • 46
  • 82
2

"most people" may be using a C style pointer cast. Most common is to cast a pointer to void * or integer. I do this a lot...

A lot times this is restricted with what I have on the other end of the program. Like passing an argument list to pthread_create, per say.

Xephon
  • 393
  • 1
  • 12
  • After thinking about it, I accepted this one because I think this is closer to the intended meaning. – leewz Dec 12 '13 at 23:27