Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
16 virtual function
1. Virtual Functions
09/04/131 VIT - SCSE
By
G.SasiKumar., M.E., (Ph.D).,
Assistant Professor
School of Computing Science and Engineering
VIT University
2. 09/04/132 VIT - SCSE
Virtual Functions
C++ matches a function call with the correct function definition
at compile time
− known as static binding
the compiler can match a function call with the correct function
definition at run time
− known as dynamic binding.
− declare a function with the keyword virtual if you want the
compiler to use dynamic binding for that specific function.
3. 09/04/133 VIT - SCSE
Virtual Functions
The virtual keyword indicates to the compiler that
− it should choose the appropriate definition of a function not by the
type of reference, but by the type of object that the reference refers
to.
4. 09/04/134 VIT - SCSE
Virtual Methods
Therefore,
− a virtual function is a member function you may redefine for
other derived classes,
− can ensure that the compiler will call the redefined virtual
function for an object of the corresponding derived class,
− even if you call that function with a pointer or reference to a base
class of the object.
A class that declares or inherits a virtual function is called a
polymorphic class.
5. Declaring virtual
prefix declaration with the virtual keyword
redefine a virtual member function in any derived class
this is called overriding
− understand the contrast with overloading
For example, the general syntax to declare a Virtual Function uses:
class classname
//This denotes the base class of C++ virtual function
{
public:
virtual void memberfunctionname() //This denotes the C++ virtual function
{
.............
............
}
};
6. More on definition
overridden function must have same name and same parameter
list
− no need to use the virtual keyword again
− return type can be different
if the parameter lists are different, they are considered different
− in this case, it is not overridden, but hidden
− hidden methods cannot be called