problem on inline virtual function.

S

shuisheng

Dear All,

If I define a virtual function to be inline, is it really inline? Or it
is inline in some cases, and not in other cases. Would you please help
me to look at the following case.

struct A
{
int i;
A() {i = 0;}
virtual void Add() {i++;}
};

struct B : public A
{
virtual void Add() {i += 2;}
};

int main()
{
A a;
a.Add(); // inline ?

B b;
b.Add(); // inline ?

A *pa = new A();
pa->Add(); // not inline?

A *pb = new B();
pb->Add(); // not inline?

return 0;
}

Thanks!

Shuisheng
 
G

Gianni Mariani

shuisheng said:
Dear All,

If I define a virtual function to be inline, is it really inline? Or it
is inline in some cases, and not in other cases. Would you please help
me to look at the following case.

It depends on the compiler, however it is nigh impossible for a compiler
to inline (as in inline the generated code) a virtual funtion.
 
V

Victor Bazarov

shuisheng said:
If I define a virtual function to be inline, is it really inline?

No function you *declare* 'inline' is really inline. There is no way
in the language to find out. The compiler will do what it wants.
Or
it is inline in some cases, and not in other cases. Would you please
help me to look at the following case.

struct A
{
int i;
A() {i = 0;}
virtual void Add() {i++;}
};

struct B : public A
{
virtual void Add() {i += 2;}
};

int main()
{
A a;
a.Add(); // inline ?

Yes, very likely.
B b;
b.Add(); // inline ?

Yes, very likely.
A *pa = new A();
pa->Add(); // not inline?

A *pb = new B();
pb->Add(); // not inline?

return 0;
}

The last two cases, I don't know, but I suspect that only the
last time the call will be non-inlined (polymorphic). Both
cases are possible to track since 'pa' and 'pb' are local objects,
and the compiler _may_ be written to track those things, but no
guarantees can be given.

Ask your compiler to generate assembly code for you and look.

V
 
K

Kevin Handy

shuisheng said:
Dear All,

If I define a virtual function to be inline, is it really inline? Or it
is inline in some cases, and not in other cases. Would you please help
me to look at the following case.

struct A
{
int i;
A() {i = 0;}
virtual void Add() {i++;}
};

struct B : public A
{
virtual void Add() {i += 2;}
};

int main()
{
A a;
a.Add(); // inline ?

B b;
b.Add(); // inline ?

A *pa = new A();
pa->Add(); // not inline?

A *pb = new B();
pb->Add(); // not inline?

return 0;
}

Thanks!

Shuisheng
I t d e p e n d s o n y o u r c o m p i l e r .
" i n l i n e " i s j u s t a h i n t ,
i t i s n o t a l a w .
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top