Tuesday, February 24, 2009

Play with const in C++

C++ Beginer always get confused by how to use const.
Here I give an example which can solidate your idea
how to use this const effectively.

The code looks like this:

#include
using namespace std;
class Shape{
public:
virtual void draw() =0;
virtual void draw() const =0;
};

class Rectangle:public Shape{
public:
virtual void draw() const;
virtual void draw();
};

void Rectangle::draw() const
{cout<<"This is const version of Rectangle.\n";};

void Rectangle::draw()
{cout<<"This is normal version of Rectangle.\n";};
void main()
{
Shape* sp=new Rectangle;

sp->draw();

const Shape* sp1=new Rectangle;

sp1->draw();

Shape* const sp2=new Rectangle;

sp2->draw();

const Shape* const sp3=new Rectangle;

sp3->draw();
}

Can you guess the result of this program? If you
are not 100% certain about your answer, please
copy this program into your editor and compile and
run it. You will get the perfect sense about how
to use the const!

As a reminder, you should notice the code:
Shape* sp=new Rectangle;
If you are writing the codes like:
Shape *sp;
sp->draw();
You will find it can not compile as Shape itself
is abstract class.

Not so fancy? Try to define a pure virtual function by adding:

void Shape::draw() const
{ cout<<"This is const version of Shape.\n";
};

void Shape::draw()
{ cout<<"This is normal version of Shape.\n";
};

void Rectangle::draw() const
{ Shape::draw();
cout<<"This is also const version of Rectangle.\n";
};

void Rectangle::draw()

{ Shape::draw();
cout<<"This is also normal version of Rectangle.\n";
};

run the codes again...