0

Suppose I have

Base.h
class Base
{
    virtual void foo() {...}
};


Derived1.h
class Derived1 : public Base
{
    virtual void foo() {...}
};


Derived2.h
class Derived2 : public Base
{
    virtual void foo() {...}
};

Header Derived1.h is included in multiple source files and Derived1 class is also used through Base interface. Since foo is virtual and is used polymorphic it can not be inlined. So it will be compiled in multiple obj files. How does linker then resolve this situation?

Andrew
  • 24,218
  • 13
  • 61
  • 90

1 Answers1

5

Member functions defined within class definition are implicitly inline(C++03 7.1.2.3).
Whether the function body actually gets inlined at point of calling is immaterial. But inline allows you to have multiple definitions of a function as long as all the definitions are same(which is disallowed by One definition rule)(C++03 7.1.2.2). The standard mandates that the linker should be able to link to (one or)many of these definitions.(C++03 7.1.2.4).

How does the linker do this?

The standard provisions for this by:

  • It mandates that the function definition should be present in each translation unit. All the linker has to do is link to the definition found in that translation unit.
  • It mandates that all definitions of this function should be exactly same, this removes any ambiguity of linking to a particular definition, if different definitions were to exist.

C++03 7.1.2 Function specifiers:
Para 2:

A function declaration (8.3.5, 9.3, 11.4) with an inline specifier declares an inline function. The inline specifier indicates to the implementation that inline substitution of the function body at the point of call is to be preferred to the usual function call mechanism. An implementation is not required to perform this inline substitution at the point of call; however, even if this inline substitution is omitted, the other rules for inline functions defined by 7.1.2 shall still be respected.

Para 3:

A function defined within a class definition is an inline function. The inline specifier shall not appear on a block scope function declaration

Para 4:

An inline function shall be defined in every translation unit in which it is used and shall have exactly the same definition in every case (3.2).

Alok Save
  • 202,538
  • 53
  • 430
  • 533