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? ?
certain cases
vfunc ( dtor) foo.cpp, main.cpp ( ), , ,
: . ODR.
ODR, ? ()?
, -, , , , ODR. vfunc, dtors, .
vfunc
. inline ( ) , . inline, . , , - , , , , . , inline ODR , inline .
inline
: , inline , ( .cpp's), . , - .
, inline. , ( ), inline. , ( , , cout - ).
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() , , , ( ).
Derived::vfunc()
Source: https://habr.com/ru/post/1568956/More articles:onDetach called when fragment - androidThe upper and lower borders are bent - cssTyrus does not connect to Android - androidRotate image in vertical direction - androidWhy does this not provide multiple definition error? - c ++Failed to call UIWebViewDelegate methods - ios8086 programming without OS; segmentation - assemblyhow to send message parameters from yii2 gridview - postVM: CG raster Data memory continues to grow - memory-managementWhat do the Prolog implementations mean under "float"? - floating-pointAll Articles