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. Note that in some other programming languages (C#, Java, ...), an equivalent code fragment will work in a different way: when creating the 'Child' object using the default constructor, the default constructor of the base class 'Base' will be called first, which will then call the overridden method 'Child::foo()'.

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

Bugs Found

Checked Projects
411
Collected Errors
14 123
This website uses cookies and other technology to provide you a more personalized experience. By continuing the view of our web-pages you accept the terms of using these files. If you don't want your personal data to be processed, please, leave this site. Learn More →
Accept