virtual functions, why ?

J

Johan

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
 
I

Ioannis Vranos

Johan said:
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.
 
R

Rolf Magnus

Johan said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,201
Messages
2,571,049
Members
47,655
Latest member
eizareri

Latest Threads

Top