what are virtual functions? what is pure virtual function? please explain with example
+5
A:
There's an excellent explanation on wikipedia.
Difference between a virtual function and a pure virtual function is that a virtual function has an implementation and you have the option to override it. A pure virtual function (abstract in Java) has no implementation and you have to implement it in a subclass (unless your subclass is also abstract).
R0MANARMY
2010-05-28 05:43:24
I thought that in C++, a virtual function of a derived class will be called even if it is typed as a base class. Is that correct?
dreamlax
2010-05-28 07:53:05
Pure virtual functions can have implementations. They remain pure, so you still have to provide another implementation in a derived class. But you can call them if you explicitly state you want the base version.
Dennis Zickefoose
2010-05-28 08:01:49
@dreamlax: That's the idea behind polymorphism, yes.
R0MANARMY
2010-05-28 11:30:25
+1
A:
/**
Virtual Function : A virtual function is a member function that is declared
within a base class and redefined by a derived class.
A base class pointer can be used to point an object of any class derived from
that base. When a base pointer points to a derived object that contains a
virtual function, C++ determines which version of that function to call based
upon the type of object pointed by the pointer.
*/
#include < iostream >
using namespace std;
class baseclass
{
public :
virtual void vfunc() { cout << "This is base class vfunc\n"; };
};
class derived : public baseclass {
public :
void vfunc() { cout << "This is derived class vfunc\n"; };
};
class derived2 : public baseclass {};
int main ()
{
class baseclass * ptr, b; // baseclass pointer and its object
class derived d; // object of derived class
class derived2 d2; // object of derived2 class
ptr = &b; // ptr points to baseclass
ptr->vfunc(); // vfunc of base class will execute
ptr = &d; // ptr points to derived class
ptr->vfunc(); // vfunc of derived class will execute
ptr = &d2; // ptr points to derived2 class
ptr->vfunc(); // vfunc of base class will execute
return 0;
}
******************************************************************************
/*
In a Pure Virtual Function, base class have no definition of virtual function
*/
#include < iostream >
using namespace std;
class baseclass
{
public :
virtual void vfunc() = 0 ; // Pure virtual function
};
class derived : public baseclass {
public :
void vfunc() { cout << "This is derived class vfunc\n"; };
};
class derived2 : public baseclass {
public :
void vfunc() { cout << "This is derived2 class vfunc\n"; };
};
int main ()
{
class derived d; // object of derived class
class derived2 d2; // object of derived2 class
d.vfunc(); // vfunc of derived class will execute
d2.vfunc(); // vfunc of derived2 class will execute
return 0;
}
Shrikant
2010-05-28 07:30:04