Re: efficiency of calling one virtual member of class from another

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi Bill,

> class Sub1 : Base {

Probably should be:

class Sub1 : public Base {

> The question is, what happens when I call f() from g()?  At -O3?  Does
> it go though the usual vector dispatch table, does it call code for the
> same instance of f directly, does it inline f in g (separately for each
> subclass), or something else?  Why?  And, has it recently or is it going
> to change?

I presume the function call goes through the usual vector dispatch table.
But if you want to know for sure, compile with --save-temps and look at the
.s file.

There could be a SubSub1 : public Sub1, which extends Sub1.  The compiler
does not know that there isn't.

If you want to get (or at least have the possibility of) inlining, you can
do this:

class Sub1
  :
  public Base
{
  ...

private:
  void* f_impl(int a) // NOT virtual
  {  
    code_f;
    return something;
  }

public:
  virtual void* f(int a)
  {
    void* result = f_impl(a);
    return result;
  }

  virtual void* g(int a)
  {
    code_g1;
    void* r = f_impl(a+1);
    code_g2;
    return r;
  }
}

Note carefully how that could affect SubSub1 (which may be adversely, or may
be beneficially... depends on the class and the method contract for f and g,
and if your team's convention of subclasses is to call their parent class
routines as well as doing their own additional behavior).

> Is there a reference I should have read rather than asking this question?

I recommend:
The C++ Programming Language (special edition) by Bjarne Stroustrup
C++ FAQ (2nd edition) by Cline, Lomow, and Girou

If you like reading standards documents:
ISO 14882

Sincerely,
--Eljay


[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux