Operator overloading inheritance with classes

78 views Asked by At

I'm new to coding and I'm trying to understand what is wrong with this program:

class Company:public Employee{
private:
    std::vector<Employee*> _table;
public:
    Company& operator+=(const Employee* emp) {
         _table.push_back(emp->clone());
          return *this;
     }
     virtual Company* clone() const {
         return new Company(*this);
     }
     virtual Company& setDescription(std::string des){
          _des=des;
     return *this;
}

with this in main:

Company* company = new Company();
a = new DeveloperEmployee(description, project);
int id = a->getID();
cout << *a << endl; //Developer ID = 2, project = hw5

company += a;

and I have this error :

   error: invalid operands of types 'Company*' and 'DeveloperEmployee*' to binary 'operator+'|
2

There are 2 answers

3
TheCppZoo On

You are applying the operator '+=' on a pointer to Company instead of a Company instance or reference to instance. Dereference the pointer, for example (*company) += a; will compile without complaint.

Please do not overload operators on pointers, overload on const references first, and take it from that.

4
R Sahu On

FWIW, using

Company& operator+=(const Employee* emp) {
     _table.push_back(emp->clone());
      return *this;
 }

to add an Employee to a Company is abuse of the semantics of the += operator.

A better option will be:

Company& addEmployee(const Employee& emp) {
     _table.push_back(emp.clone());
      return *this;
 }

Then, you can use:

Company* company = new Company();
a = new DeveloperEmployee(description, project);
int id = a->getID();
cout << *a << endl; //Developer ID = 2, project = hw5

company->addEmployee(*a);

which will make the code easier to read and follow.

Further Improvement

Instead of using a list of pointers to Employee, use a list smart pointers.

std::vector<std::share_ptr<Employee>> _table;

and

Company& addEmployee(std::shared_ptr<Employee> emp) {
     _table.push_back(emp);
      return *this;
 }

and use it as:

Company* company = new Company();
std::shared_ptr<Employee> a(new DeveloperEmployee(description, project));
int id = a->getID();
cout << *a << endl;

company->addEmployee(a);