>
>
>
V1053. Calling the 'foo' virtual functi…


V1053. Calling the 'foo' virtual function in the constructor/destructor may lead to unexpected result at runtime.

The analyzer has detected a call of a virtual function in a class constructor or destructor.

Consider the following example:
struct Base
{
  Base()
  {
    foo();
  }
  
  virtual ~Base() = default;
  virtual void foo() const;  
};

Calling the virtual method 'foo' in the constructor of the 'Base' class is in itself not necessarily a problem, but problems may arise in derived classes.

struct Child : Base
{
  Child() = default;

  virtual ~Child() = default;
  virtual void foo() const override;
};

When creating an object of type 'Child', the 'Base::foo()' method from the constructor of the base class will be called rather than the overridden method 'Child::foo()' of the derived class.

To fix the problem, we need to explicitly specify which method we want to call. This is what it will look like in the case of the 'Base' class:

struct Base
{
  Base()
  {
    Base::foo();
  }
  
  virtual ~Base() = default;
  virtual void foo() const;  
};

Now by simply looking at the code, you can tell which method exactly will be called.

Note that the usage of 'this' pointer at oneself when calling the virtual method doesn't solve the initial problem. When using 'this' it is still needed to specify what class the virtual function has to be called from:

struct Base
{
  Base()
  {
    this->foo();       // bad
    this->Base::foo(); // good
  }
  virtual ~Base() = default;
  virtual void foo() const;  
};

This diagnostic is classified as:

  • CERT-OOP50-CPP

You can look at examples of errors detected by the V1053 diagnostic.