- A class that declares or inherits a virtual function is called a polymorphic class
- A virtual funtion ensures dynamic binding.
- If a function is declared virtual, then if we have a function
with the same name and parameters in a derrived class, then that
function is automatically virtual, even if we do not declare it as
virtual in the derrived class.
struct A { virtual void f() { cout << "A::f()"; } } struct B : A { void f( int ) { cout << "B::f()"; // Hides A:f() } } struct C: B { void f() { cout <<"C::f()"; // This is always virtual } }
In the above example, B::F(int) hides A:f(). A b; b.f is illegal.
Also, C::F() is implicitly virtual.
- If a funcion has the same name as the base class function and different parameters, then it hides all functions with the same name in the base class. In the Example 1 above, B::f hides A:f
- The return type of a virtual function may be different from the
overridden one. This is called covarent virtual function. The return
types may differ provided all the following conditions are met:
1. If A::func returns a pointer or reference of type T, then B:func can return only a direct or un-ambigous derrived class from T
2. The const or volatile qualifier of type returned by B is at lease as restrictive as A
3. The return type of B::func must be complete and accessible at the point or it may be a B.
- We can call a base classes virtual function by base::func().
- A virtual function can be == 0, or pure virtual. Instances of abstract classes can not be created and an abstract class can not be used as parameters to templates.
- A derrived class can be abstract, even if it is derrived from a non-abstract class.
- We can pass a pointer or reference to an abstract class as a parameter in a function. In that function, we can even call a pure virtual method. However, we can not have an instance of an abstract class as a parameter.
- We can override a virtual function with an abstract function in a derrived class.
No comments:
Post a Comment