How to determine if a class is used polymorphically?

Suppose that in one old project (> 1M lines) there is a class with a name Basethat has two virtual functions fooandbar

class Base
{
public:
    virtual void foo();
    virtual void bar();
};

class Derived: public Base
{
public:
    virtual void foo();
    virtual void bar();
};

I suspect it is Basenot used polymorphically, therefore foo/ barshould not be virtual.

To confirm my ideas, I need to find out if there is such an operator:

Base *b = new Derived;

but if we pass a pointer among the function, it would be difficult to know, for example:

Base *f()
{
  ...
  Derived *d = /* ... */;
  ...
  return d;
}

Is there any way to do this?

+4
source share
2 answers

Make Derivedinherit privately from Base. This will prevent implicit upcasts making a Base* b = new Derived;compilation error.

0
source

:

class Base
{
    virtual void a(){};
};

class Derived : public Base 
{
    virtual void b(){};
};

:   Base * ptr = new Derived(); ptr

ptr->__vfptr    0x00eb5740 const Derived::`vftable' *
[0] 0x00eb1028 Base::a(void)    *

vtable, :

void (**vt)() = *(void (***)())ptr;

:

vt,2    0x00eb5740 const Derived::`vftable' void (void)* *
[0] 0x00eb1028 Base::a(void)    void (void)*
[1] 0x00eb10aa Derived::b(void) void (void)*

.

0

All Articles