skydoor
skydoor

Reputation: 25868

a discussion why no inline virtual function

Hi I had a discussion with my friend by asking why no inline virtual function.

My answer is inline function is at compile time and virtual function is binding at dynamic time. At compile time there is no way to know which function would call for the virtual function. So inline virtual function is not a good idea.

However, he said, it's not correct.

His answer is inline function has no address, so in virtual table, no way to put the address of the inline function, so there is no inline virtual function.

I would like to know three points:

  1. whether my answer is right? I think my answer is right.
  2. does inline function have no address? I think it has address;
  3. even inline function has a address, his answer is better than mine?

Thanks so much!

Upvotes: 4

Views: 205

Answers (1)

R. Martinho Fernandes
R. Martinho Fernandes

Reputation: 234434

I don't like either answer.

inline functions are functions that can be defined more than once (the definitions must match, though). This is why they can be put in header files. They have an address just like any other function.

virtual functions are functions that can be overriden by derived classes.

You can have a function that can be overriden by derived classes and that can have more than one definition easily:

struct foo {
    virtual void f();
}

inline void foo::f() {}

That said, any function can be inlined, i.e. have its code inserted at the point of call, instead of an actual call to it. This does not prevent taking its address in any way. Even virtual functions not marked inline can be inlined if the compiler can resolve them statically.

Upvotes: 7

Related Questions