 |
C++Talk.NET C++ language newsgroups
|
| View previous topic :: View next topic |
| Author |
Message |
Johan Guest
|
Posted: Sat Feb 26, 2005 6:39 am Post subject: virtual functions, why ? |
|
|
Hi,
I am new to C++. Why use virtual functions
class A
{
public :
A() {}
virtual ~A() {}
virtual void paint() {......}
};
class B : public A
{
public :
B() {}
virtual ~B() {}
virtual void paint() {......}
};
Why do paint have to be virtual if it has its own member function paint. Why
do you want to use virtual functions ?
John
|
|
| Back to top |
|
 |
Ioannis Vranos Guest
|
Posted: Sat Feb 26, 2005 8:35 am Post subject: Re: virtual functions, why ? |
|
|
Johan wrote:
| Quote: | Hi,
I am new to C++. Why use virtual functions
Why do paint have to be virtual if it has its own member function paint. Why
do you want to use virtual functions ?
|
Consider the following program:
#include <iostream>
class Drawing
{
public :
virtual ~Drawing() {}
virtual void paint()
{
std::cout<<"Drawing::paint() was called!n";
}
};
class Rectangular: public Drawing
{
public :
virtual ~Rectangular() {}
virtual void paint()
{
std::cout<<"Rectangular::pain() was called!n";
}
};
void somefunc(Drawing *p)
{
p->paint();
}
int main()
{
Rectangular r;
somefunc(&r);
}
somefunc() processes a pointer to a Drawing object, and the appropriate
paint() specialisation of a Drawing object is called.
Had paint() been non-virtual, Drawing::paint() would have been called.
--
Ioannis Vranos
http://www23.brinkster.com/noicys
|
|
| Back to top |
|
 |
Rolf Magnus Guest
|
Posted: Sat Feb 26, 2005 10:56 am Post subject: Re: virtual functions, why ? |
|
|
Johan wrote:
| Quote: | Hi,
I am new to C++. Why use virtual functions
class A
{
public :
A() {}
virtual ~A() {}
virtual void paint() {......}
};
class B : public A
{
public :
B() {}
virtual ~B() {}
virtual void paint() {......}
};
Why do paint have to be virtual if it has its own member function paint.
Why do you want to use virtual functions ?
|
The keyword is polymorphism. This is a very important concept of C++ and
object oriented programming in general. The idea is that you can e.g. do
something like:
A* objects[2];
objects[0] = new B;
objects[1] = new OtherClassDerivedFromA;
So you can store objects of different types. But now there is a problem.
What happens if you do:
objects[0]->paint();
objects[1]->paint();
objects[0] and objects[1] are not the same type, but they are both stored
using a pointer to A. If paint() isn't virtual, A::paint() gets called. If
you make paint() virtual in A, the runtime system automatically finds out
which derived class the object is really of and calls the paint() of that
class.
|
|
| Back to top |
|
 |
EventHelix.com Guest
|
|
| Back to top |
|
 |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
|