Saikiran Nathan
Saikiran Nathan

Reputation: 11

Linker Error C++ vtable

I am trying to define an explicit constructor in c++ but im getting thrown a linker error with vtable.

This is what i have so far

class Sphere : public Circular{
public:
    Sphere(double r);
    string name() const {return "Sphere";}
    double volume() const;
    double surface_area() const;
};

Sphere:: Sphere(double r): Circular(r){}

This is what the error gives me:

  "vtable for Sphere", referenced from:
  Sphere::Sphere(double) in main.o
  NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.

But if I do it inline like this:

class Sphere : public Circular{
public:
    Sphere(double r):Circular(r){} <--
    string name() const {return "Sphere";}
    double volume() const;
    double surface_area() const;
};

Then it doesnt throw any errors. Here is my Circular class and GeometricSolid class for reference:

class GeometricSolid{
public:
    virtual string name() const = 0;
    virtual double volume() const = 0;
    virtual double surface_area() const = 0;
    virtual ~GeometricSolid(){};
};
class Circular : public GeometricSolid{
protected:
    double radius;
public:
    virtual string name() const = 0;
    virtual double volume() const = 0;
    virtual  double surface_area() const =0;
    Circular(double r);

};

Thanks.

Upvotes: 0

Views: 66

Answers (1)

Labonneguigue
Labonneguigue

Reputation: 133

The issue is that in your Sphere class, the functions volume() and surface_area() remain undefined. Therefore the compiler doesn't issue any vtable for the Sphere class.

If you want to keep Sphere abstract, define it as such:

class Sphere : public Circular{
public:
    Sphere(double r);
    string name() const {return "Sphere";}
    virtual double volume() const = 0;
    virtual double surface_area() const = 0;
};

Sphere::Sphere(double r): Circular(r){}

Otherwise provide a definition for these functions.

The reason behind that is that the vptr (virtual pointers) in the vtable must point to somewhere.

Upvotes: 1

Related Questions