0

Hello I am trying to write some c++(17) program to manipulate objects. However, I am stuck with code because compiler generates "undefined reference to vtable for constructors(Shape, Rectangle, Triangle)". Here you have my code that generates the error. I have really no idea what causes it.

#include <iostream>

class Shape {
private:
    int x = 0, y = 0;

public:
    Shape(int x1, int y1)
    {
        this->x = x1;
        this->y = y1;
    };
    virtual float area();
    int getX() const
    {
        return x;
    };
    int getY() const { return y; };

    void setX(int x1);
    virtual ~Shape();
};

void Shape::setX(int x1) { x = x1; }

class Rectangle : public Shape { //inheritage of Shape

public:
    Rectangle(int x, int y)
        : Shape(x, y){};
    float area() { return getX() * getY(); }
    virtual ~Rectangle();
};

class Triangle : public Shape { //inheritage of Shape
public:
    Triangle(int x, int y)
        : Shape(x, y){};
    float area() { return 0.5 * getX() * getY(); }
    virtual ~Triangle();
};

Shape::~Shape()
{
}
Triangle::~Triangle()
{
}
Rectangle::~Rectangle()
{
}

int main()
{

    Rectangle rectangle(2, 3);
    Triangle triangle(3, 3);
    std::cout << rectangle.area() << std::endl; //6
    std::cout << triangle.area() << std::endl; //4.5
    return 0;
}

drescherjm
  • 10,365
  • 5
  • 44
  • 64
  • I know the semicolons after the function definitions is unnecessary (`int getY() const { return y; };` could just be `int getY() const { return y; }`) but does that cause the problem here? – Nathan Pierson Nov 03 '20 at 15:17
  • 6
    Supplying an implementation for `Shape::area` or making it pure virtual fixes it for me. – Retired Ninja Nov 03 '20 at 15:17
  • Oh yeah, In the declaration of the class Shape, "virtual float area()= 0;" solves the issue! Thank you so much! – Donald Mbogni Nov 03 '20 at 15:55
  • If a class has any virtual member functions, it *probably* has a virtual destructor. Make sure the virtual destructor is the very first non-inline virtual function. Order is important. That way the vtable will be generated in the translation unit that defines the destructor. – Eljay Nov 03 '20 at 16:53

0 Answers0