Why does the linker give me an error in the virtual case, but not in the non-virtual case?

When I have something like this:

class A
{
  virtual void rat();
};

class B : public A
{
  virtual void rat() { ; } //implemented!
};

int main(int argc, char **argv)
{
  A *a = new B;
  delete a;
}

I get linker errors:

unless I make the base rat pure virtual.

However, when I have this:

class A
{
  public:
  void rat();
};

int main(int argc, char **argv)
{
  A a;
}

This compiles fine and does not give me a link to an undefined link unless I explicitly try to call the rat function in my main ( a.rat();). What is the rule for unrealized virtual functions of a base class, which, however, are implemented in a derived class, as in the first code fragment with an error?

+3
source share
5 answers

, ++ vtables A B. A vtable, A::rat() - , .

A , A::rat , .

, , , A::rat , vtable ( ).

+5

.

class A 
{ 
   public: void rat(); 
};

int main(int argc, char **argv) 
{ 
  A a; 
}

- . , , /, , .

, - rat() A.

A a;
a.rat();   // Compiler passes. But linker bombs.

.

+4

A::rat() , .

+2

ODR: , ODR, .

ODR- , , - . , .

: virtual ( ) ODR-.

+2

++ . ++ 03 ยง10.3/8:

, , โ€‹โ€‹ (10.4) , ; (3.2).

( = 0 ), .

, , , . ++ 03 ยง3.2/2-3 ()

2) , , (. 5.19), sizeof (5.3.3) typeid lvalue (5.2.8). , - . - , . [...]

3) - , , ; . , ( ), (. 12.1, 12.4 12.8). , .

, , , . , , - , .

. , ?.

+2
source

All Articles