Virtual Funtionality

class A
{
public:
virtual void foo();
};
class B: public A
{
private:
virtual void foo();
};
Is there any problem with the code above? If not then what will happen?
There are different different scenarios are given as in above code for virtual functionality. What should be the basics behind all such questions to answer?
The key to understanding this are the class access specifiers:
 
public, protected, private

Hint, what happens when a virtual function is called using a base class pointer?

Say your class B declares method foo as public.
Understand should happen when you code this?

1
2
3
4
A* base = new B;

base->foo();
delete base;


While you're on this topic, read up on why you need virtual destructors!

--
Rajinder Yadav <labs@devmentor.org>

DevMentor Labs
http://labs.devmentor.org
Creating Amazing Possibilities
Last edited on
I think part of what he's asking if class B can declare A's virtual function as a virtual too.
If you are declaring a virtual function of a class when you should declare the class destructor also as virtual.
Public inheritance means the relation "is as". So if the base class has a public method then a derived class should have the same public method that to be "as base".
In your example there is some contradiction. For example

A *pa = new B;

pa->foo(); // will be successfuly compiled

B *pb = new B;

pb->foo(); // error. B::foo is private.

I think part of what he's asking if class B can declare A's virtual function as a virtual too.

You certainly can, although it won't make any difference. Once you've declared a method as virtual in a base class, then all methods that override it in derived classes are considered virtual, regardless of whether you use the virtual keyword in the declarations of those methods in the derived classes. If it's virtual in the base class, it's virtual from then on.

I would say that it's good practice to put the virtual keyword in there anyway, as it makes it obvious at a glance that it's virtual, without needing to look at the base class.

Topic archived. No new replies allowed.