class base {
public:
void virtual fn(int i) {
cout << "base" << endl;
}
};
class der : public base{
public:
void fn(char i) {
cout << "der" << endl;
}
};
int main() {
base* p = new der;
char i = 5;
p->fn(i);
cout << sizeof(base);
return 0;
}
Here signature of function fn defined in base
class is different from signature of function fn()
defined in der
class though function name is same.
Therefore, function defined in der
class hides base
class function fn()
. So class der
version of fn cannot be called by p->fn(i)
call; It is fine.
My point is then why sizeof
class base
or der
is 4
if there is no use of VTABLE pointer? What is requirement of VTABLE pointer here?
If you don't override a pure virtual function in a derived class, that derived class becomes abstract: class D2 : public Base { // no f1: fine. // no f2: fine, we inherit Base::f2.
In addition, if you do not override a virtual member function in a derived class, a call to that function uses the function implementation defined in the base class. A function that has a deleted definition cannot override a function that does not have a deleted definition.
It is not mandatory for the derived class to override (or re-define the virtual function), in that case, the base class version of the function is used. A class may have virtual destructor but it cannot have a virtual constructor.
VPTR : After creating Vtable address of that table gets stored inside a pointer i.e. VPTR (Virtual Pointer). When you create an object of a class which contains virtual function then a hidden pointer gets created automatically in that object by the compiler.
Note that this is highly implementation dependent & might vary for each compiler.
The requirement for presence of vtable
is that the Base class is meant for Inheritance and extension, and a class deriving from it might override the method.
The two classes Base and Derived might reside in different Translation Unit and the compiler while compiling the Base class won't really know if the method will be overidden or not. So, if it finds the keyword virtual
it generates the vtable
.
The vtable is usually not only used for virtual functions, but it is also used to identify the class type when you do some dynamic_cast
or when the program accesses the type_info
for the class.
If the compiler detects that no virtual functions are ever overridden and none of the other features are used, it just could remove the vtable pointer as an optimization.
Obviously the compiler writer hasn't found it worth the trouble of doing this. Probably because it wouldn't be used very often, and because you can do it yourself by removing the virtual
from the base class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With