Non-built-in virtual function defined in the header file

One definition rule states that:
In an entire program, an object or non-built-in function cannot have more than one definition. (from Wikipedia)

Well, I know that if a member function is defined in the header file, it is implicitly inlined, and this is normal with ODR.

But what about virtual functions? We know that if a virtual function is called polymorphically, it cannot be inlined. if such a virtual function is deleted in the header file, will this violate ODR?

For instance:

//derived.hpp
#include <iostream>
class Base {
public:
  virtual ~Base() {}
  virtual void vfunc() {
    std::cout << "Base::vfunc()\n";
  }
};

class Derived : public Base {
public:
  virtual ~Derived() {}

  virtual void vfunc() {
    std::cout << "Derived::vfunc()\n";
  }
};

//foo.cpp

#include "derived.hpp"
void func() {
  Base* ptr = new Derived();
  ptr->vfunc(); //polymorphic call, can't be inlined
  delete ptr;

  ptr = new Base();
  ptr->vfunc();
  delete ptr;
}
//main.cpp

#include "derived.hpp"

int main() {
  Base* ptr = new Derived();
  ptr->vfunc(); //polymorphic call, can't be inlined
  delete ptr;

  ptr = new Base();
  ptr->vfunc();
  delete ptr;
  return 0;
}

I am wondering:

vfunc (and dtor) is called both in foo.cpp and main.cpp is polymorphic (not built-in), which means that it is detected twice in the whole program, so it violates ODR, right? How does this compile (link)?

I just saw this:

. , , . , ( )

certain cases? ?

+3
2

vfunc ( dtor) foo.cpp, main.cpp ( ), , ,

: . ODR.

ODR, ? ()?

, -, , , , ODR. vfunc, dtors, .

. inline ( ) , . inline, . , , - , , , , . , inline ODR , inline .

: , inline , ( .cpp's), . , - .

+2

, inline. , ( ), inline. , ( , , cout - ).

, , - :

class Base {
public:
  virtual ~Base() {}
  virtual void vfunc();
};

class Derived : public Base {
public:
  virtual ~Derived() {}

  virtual void vfunc();
};



void Base::vfunc()
{
  {
    std::cout << "Base::vfunc()\n";
  }
}

void Derived::vfunc()
{
  {
    std::cout << "Derived::vfunc()\n";
  }
}

ODR, Derived::vfunc() , , , ( ).

+1

Source: https://habr.com/ru/post/1568956/


All Articles