0

I was going through the virtual functions and vtables and got a doubt. Suppose I have code something as below:

class base
{ 
    public:
    virtual void fun(){}
};
class derived : private base
{ 
    public:
    void fun(){}
};

With the scope rule when base class is derived as private then all it's members becomes private of derived class. Will the compiler inserted vptr(pointer to vtable) also become private to derived class?

Vinod
  • 115
  • 11
  • 5
    the `vptr` is a behind-the-scenes concept. It does not "become private" because you can neither directly access it nor know its layout. However, what it does mean is that people who have a `derived object;` cannot access it as (nor convert it to...) a `base * b = &object;` because the compiler will complain that it's a private inheritance. – inetknght Apr 14 '16 at 17:56
  • @SergeyA because you disagree with the practice I quoted from someone else or because of the details of vtable usage? – zetavolt Apr 14 '16 at 18:04
  • Since people are talking about why private virtuals [there is a Stackoverflow answer](http://stackoverflow.com/a/3978552/16800) that goes into detail about their uses. – Guvante Apr 14 '16 at 18:19

1 Answers1

2

It retains it's vtable of function ptr entries, and although it's "improper" to talk about the vtable in terms of private or public, because it's a compiler detail, it will always exist and be "public".

To extend that point further, I'm not familiar with the spec on the matter but I believe (based on looking at a lot of generated assembly of C/C++ code from different compilers) monomorphization of the function in a virtual, even if no specialization is needed (at runtime or otherwise), is forbidden.

zetavolt
  • 2,989
  • 1
  • 23
  • 33
  • 3
    Another misguided **best practice**. Private virtuals are wonderful tool, and the reason not to use the tool simply because someone is confused is dubious at best. – SergeyA Apr 14 '16 at 18:02
  • I can sympathize with disagreements over best practice but is there something wrong with the actual answer (vtable implementation)? – zetavolt Apr 14 '16 at 18:06
  • Remove the very wrong part of private virtual functions and it will be the OK answer. – SergeyA Apr 14 '16 at 18:08
  • @SergeyA No problem, I thought it was a fairly established practice (which is why I was quoting it) -- what do you use private virtuals for? – zetavolt Apr 14 '16 at 18:09
  • 1
    The "template method pattern" is usually implemented with private virtuals. Pure virtuals which do not need to be called from outside are best kept private. – Alexandre C. Apr 14 '16 at 18:12
  • They implement so-called template method pattern. For easily available examples, I refer you to iostreams in std. – SergeyA Apr 14 '16 at 18:13