Skip to main content

IAR Embedded Workbench for RX 5.20

CPU-ctor-call-virt (C++ only)

In this section:
Synopsis

A virtual member function is called in a class constructor.

Enabled by default

Yes

Severity/Certainty

Medium/High

mediumhigh.png
Full description

When an instance is constructed, the virtual member function of its base class is called, rather than the function of the actual class being constructed. This might result in the incorrect function being called, and consequently incorrect data or uninitialized elements. This check is identical to MISRAC++2008-12-1-1_a, MISRAC++2023-15.1.1_a.

Coding standards
CERT OOP30-CPP

Do not invoke virtual functions from constructors or destructors

MISRA C++ 2008 12-1-1

(Required) An object's dynamic type shall not be used from the body of its constructor or destructor.

MISRA C++ 2023 15.1.1

(Required) An object's dynamic type shall not be used from within its constructor or destructor

Code examples

The following code example fails the check and will give a warning:

#include <iostream>

class A {
public: 
  A() { f(); }  //virtual member function is called
  virtual void f() const { std::cout << "A::f\n"; }
};

class B: public A {
public:
  virtual void f() const { std::cout << "B::f\n"; }
};

int main(void) {
  B *b = new B();
  delete b;
  return 0; 
}

The following code example passes the check and will not give a warning about this issue:

#include <iostream>

class A {
public: 
  A() { }  //OK - contructor does not call any virtual
           //member functions
  virtual void f() const { std::cout << "A::f\n"; }
};

class B: public A {
public:
  virtual void f() const { std::cout << "B::f\n"; }
};

int main(void) {
  B *b = new B();
  delete b;
  return 0; 
}