Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++, is there a consensus regarding default behavior vs explicit code?

Tags:

c++

I'm wondering if there's any reason to explicitly write code that does the same as default behavior of C++.

Here's some code:

class BaseClass
{
public:
    virtual ~BaseClass() {}

    virtual void f() { /* do something */ }
};

class ExplicitClass
    : public BaseClass
{
public:
    ExplicitClass()
        : BaseClass()   // <-- explicit call of base class constructor
    {
        // empty function
    }

    virtual ~ExplicitClass() {}  // <-- explicit empty virtual destructor

    virtual void f() { BaseClass::f(); }  // <-- function just calls base
};

class ImplicitClass
    : public BaseClass
{    
};

I'm mainly curious in the realm of refactoring and a changing code base. I don't think many coders intend to write code like this, but it can endup looking like this when code changes over time.

Is there any point to leaving the code present in the ExplicitClass? I can see the bonus that it shows you what is happening, but it comes across as lint-prone and risky.

Personally I prefer to remove any code that is default behavior code(like ImplicitClass).

Is there any consensus favoring one way or the other?

like image 461
Matt Avatar asked Sep 20 '12 22:09

Matt


1 Answers

There are two approaches to this issue:

  1. Define everything even if compiler generates the same,
  2. Does not define anything which compile will do better.

The believers of (1) are using rules like: "Always define Default c-tor, Copy C-tor, assignment operator and d-tor".

(1) believers think it is safer to have more than to miss something. Unfortunately (1) is especially loved by our managers - they believe it is better to have than don't have. Sp such rules like this "always define big four" go to "Coding standard" and must be followed.

I believe in (2). And for firms where such coding standards exist, I always put comment "Do not define copy c-tor as compiler does it better"

like image 66
PiotrNycz Avatar answered Sep 17 '22 20:09

PiotrNycz