I'm having trouble with a basic polymorphism feature. I have a base class with a draw function and two derived classes each with a draw function implemented as well. I'd like to use a base class pointer pointing to a derived class, to use the base class's implementation of the draw function. Then I would like to use the derived classes draw function.
#include <iostream>
#include <string>
#include <fstream>
#ifndef SHAPEHEADER_H
#define SHAPEHEADER_H
using namespace std;
class Shape {
public:
Shape(float, float);
virtual ~Shape() = default;
virtual float draw() const { return 94.9; };
private:
float a;
float b;
};
#endif // !SHAPEHEADER_H
#include <iostream>
#include <string>
#include <fstream>
#include "ShapeHeader.h"
#ifndef CIRCLEHEADER_H
#define CIRCLEHEADER_H
using namespace std;
class Circle : public Shape{
public:
Circle(float);
float draw() const override { return pi * radius*radius; };
private:
float radius;
static float pi;
};
#endif // !SHAPEHEADER_H
Shape s0(1.0, 1.0);
Circle c0(1.0);
Square sq0(3.0, 4.0);
Shape *shape0 = &s0;
Shape *shape1 = &c0;
Circle *circle0 = &c0;
cout << "Shape:" << shape0->draw() << endl;
cout << "Circle:" << circle0->draw() << endl;
system("PAUSE");
cout << "Pointing to circle and square with shape pointer" << endl;
cout << "Circle:" << shape1->draw() << endl;
system("PAUSE");
This does not produce the shape draw output it outputs the circle draw function.
On Tutorialspoint.com they have the following code:
#include <iostream>
using namespace std;
class Shape {
protected:
int width, height;
public:
Shape( int a = 0, int b = 0){
width = a;
height = b;
}
int area() {
cout << "Parent class area :" <<endl;
return 0;
}
};
class Rectangle: public Shape {
public:
Rectangle( int a = 0, int b = 0):Shape(a, b) { }
int area () {
cout << "Rectangle class area :" <<endl;
return (width * height);
}
};
class Triangle: public Shape {
public:
Triangle( int a = 0, int b = 0):Shape(a, b) { }
int area () {
cout << "Triangle class area :" <<endl;
return (width * height / 2);
}
};
// Main function for the program
int main() {
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);
// store the address of Rectangle
shape = &rec;
// call rectangle area.
shape->area();
// store the address of Triangle
shape = &tri;
// call triangle area.
shape->area();
return 0;
}
Why is it when they use a base class pointer pointing to an inherited class and they invoke draw, which all three poses, their program outputs the base class function. In my code, I had the same setup, a base class pointer to a inherited class object and it would output the inherited class draw. Thank you in advance.