Hi,
When you include a header file, the header file is inserted at the spot of the include statement. And, a header file can only appear once in a file. In your program, in the file Square.cpp, you include Square.h. If you take Square.h and insert it in Square.cpp, you get this:
Square.cpp
-------------
Code:
//#include "Square.h":
#include "Shape.h"
class Square: public Shape {
public:
Square(int l, int w): Shape(l,w){}
int area(void);
};
#include "Shape.h"
int Square::area (void) {
return length*width;
}
But, now you are including Shape.h twice, which produces this:
Square.cpp
-------------
Code:
//#include "Shape.h":
class Shape {
protected:
int length, width;
public:
Shape (int l, int w) { length = l; width = w;}
virtual int area (void) = 0;
};
class Square: public Shape {
public:
Square(int l, int w): Shape(l,w){}
int area(void);
};
//#include "Shape.h":
class Shape {
protected:
int length, width;
public:
Shape (int l, int w) { length = l; width = w;}
virtual int area (void) = 0;
};
int Square::area (void) {
return length*width;
}
C++ does not tolerate redeclarations of the same class or variable, so that is the reason you can only include a header file once. As it turns out, including header files can be a tricky business when a program has lots of files: it can be nearly impossible to track what header files are being included by other header files you are including that themselves include yet other header files. C++ has a solution: you can use inclusion guards around all your header files. Then, if a header file has already been included once in a file, it won't be included again. You should make it a habit of putting inclusion guards around the code in your header files, and they look like this:
Code:
#ifndef __MYCLASS_H__
#define __MYCLASS_H__
//your code here
endif //__MYCLASS_H__
This part:
__MYCLASS_H__
is just a name and it can be anything. Normally, you use the name of your header file.