PDA

View Full Version : diffrence between void and virtual void



raphaelf
23rd February 2006, 13:40
Hello everybody,

can somebody say me when i have to use virtual void?And the difference between virtual void and void?


thx

jpn
23rd February 2006, 13:50
The virtual keyword defines that a class function may be overridden in a derived class.
So the derived class may have an implementation of a function with same name and argument list but with different/extended functionality.

Edit: http://www.cppreference.com/keywords/virtual.html

jacek
23rd February 2006, 13:58
virtual keyword has nothing to do with return type of a method. It only tells that the following method is virtual (you can skip virtual in subclasses).

Try this:
#include <iostream>

class A
{
public:
A() {}
void nonVirt() { std::cerr << "A::nonVirt()" << std::endl; }
virtual void virt() { std::cerr << "A::virt()" << std::endl; }
virtual ~A() {}
};

class B : public A
{
public:
void nonVirt() { std::cerr << "B::nonVirt()" << std::endl; }
void virt() { std::cerr << "B::virt()" << std::endl; }
};

int main()
{
A a;
B b;
A *ptr = &b;

a.nonVirt();
a.virt();
b.nonVirt();
b.virt();
ptr->nonVirt();
ptr->virt();

return 0;
}