Two Virtual Functions

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
{
...
virtual void f(int a){definition 1};
...
}

class B:public class A
{
...
virtual void f(int a){definition 2}; //Overriding function f() in Derived Class
...
}


If I remember correctly, the function void f is virtual by default in the derived class.

It is just a matter of style when you write "virtual" for the derived version. It's simply there for verbosity.

Carlo
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?
Last edited on
I am just giving it a try. Please correct me if I am wrong.

1. Base Class Object (A a)

a->f();

This calls derived class function. If in case there there is no f() in derived class, it calls the f() in base class

2. Derived class Object (B b)

b->f();

This calls derived class function. If in case there there is no f() in derived class, it will result in error - No such function exists, may be?

3. Object Slicing A *a = new B();

1
2
a->f(); //Calls Derived Class Function f()
a->A::f(); //Calls Base Class Function f() 


Someone Correct me, please?

Also one final question, I used a-> A::f() to access Base Class Function. Is there any other way with out using Scope Resolution Operator?

Last edited on
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.
Topic archived. No new replies allowed.