One of my friends asked me this question. Neither I nor he knows the answer.
What will happen if I use virtual keyword in the derived class as well? Is it possible? If it is not possible, please tell me WHY? and if it is possible kindly tell me WHEN and WHY will we use something like this, please?
1 2 3 4 5 6 7 8 9 10 11 12 13
class A
{
...
virtualvoid f(int a){definition 1};
...
}
class B:publicclass A
{
...
virtualvoid f(int a){definition 2}; //Overriding function f() in Derived Class
...
}
I agree with cdel. I believe you could remove the virtual from both functions and still get the same effect. However, it might affect how the function lookup is done when void f(int a) is called, but i'm not 100% sure on this. Obviously it is better to put the virtual there so that anyone reading your code (and possibly the compiler) knows explicitly that the function is likely to be overriden in any derived classes.
Thanks for you replies friends. As you say if the function f() is virtual both in the Base class and also in the derived class, how do I call the base class function f() and also derived class function f() using
1. Base Class Object (A a)
2. Derived class Object (B b)
3. Object Slicing A *a = new B();
Using all the three objects mentioned above, I want to call both the base class object and also the derived class object. How do I do it, anyone please?
1. is incorrect. If a is a pointer to an object of type A then it will call the function in A. It has no knowledge of any derived classes
2. again incorrect. The derived class inherits the function from the base class. So it will call the base class function if you fail to provide one in the derived class.
3. is correct!
As far as I know the scope resolution operator is the only way to avoid the virtual function resolution.