0

I am new to virtual functions in c++. To understand them I created two classes : CommissionEmployee(Employee gets commission on sale - Base class) and BaseplusCommissionEmployee(Gets a base salary as well - Derived class).

I declared the functions print() and earning in both classes as virtual. But at compilation I get the following error : undefined reference to `vtable for CommissionEmployee'

Following this answer(Linking error: undefined reference to `vtable for XXX`) I got some idea that I should define non pure virtual functions during declaration itself. But I separate the class definition and function definitions into separate header and cpp file. So should I define the virtual function in header wouldn't it give compilation error?

header file for CommissionEmployee :

#ifndef CommissionEmployee_h // CommissionEmployee_inheritance.h
#define CommissionEmployee_h
#include<string>

using namespace std;

class CommissionEmployee
{
    public :
    CommissionEmployee(const string&, const string&, const string&, double =0.0, double =0.0);

    void setfirstname(const string &name);
    void setlastname(const string &name);
    void setsocialsecuritynum(const string&);
    void setgrosssales(double );
    void setcommisionrate(double);
    
    string getfirstname() const;
    string getlastname() const;
    string getsocialsecuritynum() const;
    double getgrosssales() const;
    double getcommisionrate() const;

    virtual double earning() const;
    virtual void print() const;

    private :
    string firstname;
    string lastname;
    string socialsecuritynum;
    double grosssales;
    double commisionrate;
};

#endif

Header for BaseplusCommissionEmployee :

#include"CommissionEmployee_inheritance.h"

class BaseplusCommissionEmployee : public CommissionEmployee
{   
    public:
    BaseplusCommissionEmployee(const string&, const string&, const string&,double=0 , double=0, double=0);

    
    void setbasesalary(double);
    
    double getbasesalary() const;

    virtual double earning() const;
    virtual void print() const;

    private:
  
    double basesalary;
};
  • The answer to the other question says *"In particular, G++ emits the vtable along with the implementation of the first-declared non-inline function in a class. "*. So have you implemented `earning()` for both classes? And are you linking with **both** object files? – BoP Jan 30 '22 at 08:36
  • Have you implemented all the declared methods? How are you compiling the code? Please show a [mre] – Alan Birtles Jan 30 '22 at 08:55

0 Answers0