In my C++ project I have a 'Shape' class and its child class, 'Square' in the .h file:
class Shape {
public:
Shape();
Shape(int, int, string);
virtual ~Shape();
virtual void draw();
private:
int length, width;
string colour;
};
class Square : public Shape {
public:
Square(int, int, string);
void draw();
};
In the .cpp file I implemented the constructors etc.
Shape::Shape() : length(0), width(0) {}
Shape::Shape(int len, int wid, string col) : length(len), width(wid), colour(col) {}
Shape::~Shape() {} //destructor
virtual void Shape::draw(){};
Square::Square(int len, int wid, string col) : Shape(len, wid, col) {}
void Square::draw() {cout << "I am drawing a square" << endl;};
I'm trying to test it in the main function as follows, just by pushing a single square.
int main() {
int count(0);
vector<Shape*> shapes;
shapes.push_back(new Square(10, 10, "orange"));
for (Shape* shp : shapes) {
cout << "\nShape " << count++ << ":";
shp->draw();
} // end for
for (Shape* shp : shapes)
delete shp;
return 0;
}
Ideally, the output would look like this:
Shape 0: I am drawing a square
However, all it's outputting is
Shape 0:
If I put some output into void Shape::draw(){};
like void Shape::draw(){cout << "I am just a shape" <<endl;};
The output is Shape 0:I am just a shape.
This tells me that the function just ends at the Shape::draw() function without getting overwritten. The code does build fine, but what is happening in .cpp and .h that's stopping the inheritance? Edit: Declaring the draw function as virtual hammered in the nail for the coffin.