Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement pure virtual function in C++

Tags:

c++

I think the implementation of virtual function is talked about a lot. My question is what about pure virtual function? However it is implemented? In virtual table, how to tell it is a pure or non-pure? What the difference between pure virtual function and virtual function with implementation?

like image 916
skydoor Avatar asked Mar 11 '10 21:03

skydoor


2 Answers

There is no usually no implementation difference between pure and non-pure virtual functions. Provided a pure-virtual function is defined, it acts like any other virtual function. If it is not defined, it only causes a problem if it is explicitly called.

There are two major differences in behaviour, but there is usually no impact on the implementation of the virtual function mechanism itself. The compiler must not allow you to construct an object of a type which has pure virtual functions that don't have a non-pure final override in their inheritance hierarchy and any attempt to make a virtual call to a pure virtual function directly or indirectly from an object's constructor or destructor causes undefined behaviour.

like image 79
CB Bailey Avatar answered Sep 29 '22 20:09

CB Bailey


virtual void foo() = 0;

A pure virtual function is still a virtual function, so it would be in the vtable, but the compiler doesn't require an implementation for it, and will prohibit instantiation of the base class that declares the pure virtual. Since you can still dereference pointers of type of the abstract base class, the virtual table has to have an entry, for polymorphism and runtime binding.

Does that help?

like image 38
codenheim Avatar answered Sep 29 '22 22:09

codenheim