Overload a method or use default values? c++

后端 未结 4 1264
再見小時候
再見小時候 2021-01-04 01:11

I\'m still relatively new to C++ and I can\'t seem to figure out the difference in the following two ways of coding a function that may take one parameter or maybe two or th

4条回答
  •  北荒
    北荒 (楼主)
    2021-01-04 01:39

    The compiler doesn't care which of these you use. Imagine that you wrote it as two constructors, and they ended up about 20 lines long. Further imagine that 19 of the lines were identical, and the different line read

    foo = 0;
    

    in one version and

    foo = optional;
    

    in the other. In this situation, using an optional parameter makes your code far more readable and understandable. In another language, that didn't have optional parameters, you'd implement this by having the one-parameter version call the two parameter version and pass zero to it as the second parameter.

    Now imagine a different pair of constructors or functions that again are about 20 lines long but are entirely different. For example the second parameter is an ID, and if it's provided, you look stuff up in the database and if it's not you set values to nullptr, 0, and so on. You could have a default value (-1 is popular for this) but then the body of the function would be full of

    if (ID == -1)
    {
        foo = 0;
    }
    else 
    {
        foo = DbLookup(ID);
    }
    

    which could be hard to read and would make the single function a lot longer than the two separate functions. I've seen functions with one giant if that eseentially split the whole thing into two separate blocks with no common code, and I've seen the same condition tested 4 or 5 times as a calculation progresses. Both are hard to read.

    That's the thing about C++. There are lots of ways to accomplish most things. But those different ways serve different purposes, and once you "get" the subtle differences, you will write better code. In this case "better" means shorter, faster (all those ifs cost execution time), and more expressive - people reading it can understand your intentions quickly.

提交回复
热议问题