Search code examples
c++openglsubclassglutcurves

Issue overriding c++ class for drawing curve


I'm trying to implement a program where lines will be drawn from point to point when a user clicks on a screen. I have a Polyline class, which is a subclass of a Freeform class, which is a subclass of a Curve class. The draw method of the Curve superclass usually calls getPoint, which will get a weighted point for the curve at that specific point. However, in the case of the draw method for Polyline, I'm trying to override the curve class to just get the point that the user is clicking on (as you can see, the draw method of the Polyline class never calls getPoint). However, when I debug the code I see that getPoint is still being called when I try to draw a polyline. Any suggestions?

class Curve {

public:
    virtual float2 getPoint(float t)=0;

    void draw(){

        glBegin(GL_LINE_STRIP);
        for (float i = 0; i < 1; i+=.01) {
            float2 point = getPoint(i);
            float x = point.x;
            float y = point.y;
            glVertex2d(x, y);

        }
        glEnd();
        }; 
    };

class Freeform : public Curve
{
protected:
    std::vector<float2> controlPoints;

public:
    virtual float2 getPoint(float t)=0;
    virtual void addControlPoint(float2 p)
    {
        controlPoints.push_back(p);
    }
    void drawControlPoints(){
        glBegin(GL_POINTS);
        for (float i = 0; i < controlPoints.size(); i++) {
            float2 point = controlPoints.at(i);
            float x = point.x;
            float y = point.y;
            glVertex2d(x, y);

        }
        glEnd();// draw points at control points
    }
};

class Polyline : public Freeform {
public:
    float2 getPoint(float t) {
        return float2(0.0, 0.0);
    }
    //we add a control point (in this case, control point is where mouse is clicked)
    void addControlPoint(float2 p)
    {
        controlPoints.push_back(p);
    }
    //trying to override Curve draw method
    void draw(){
        glBegin(GL_LINE_STRIP);
            for (float i = 0; i < controlPoints.size(); i++) {
            float2 point = controlPoints.at(i);
            float x = point.x;
            float y = point.y;
            glVertex2d(x, y);
        }
        glEnd();
    };
};

Solution

  • //trying to override Curve draw method
    

    The comment above pretty much says it all; you are "trying" to override void Curve::draw (), but fail to do so since the member-function is not previously declared virtual.


    Solution

    • Declare void Curve::draw () as virtual.
    • If or later, look into (and make use of) the keyword override.