Google Mock: “no appropriate default constructor available”?

风流意气都作罢 提交于 2019-12-05 05:27:40

You can just add a constructor to your mock that delegates to the Employee constructor:

 class MockEmployee : public Employee {
     public:
         MockEmployee(PensionPlan* pension_plan, const char* full_name)
         : Employee(pension_plan, full_name) {}
         // ...
 };

Then construct MockEmployee like you would construct Employee. However, there are a couple things that can be improved about this code that I would highly recommend and that would simplify this:

  1. Make Employee pure virtual (with a protected default constructor).
  2. Rename the current Employee implementation to a name that describes the kind of employee (e.g. FullTimeEmployee or EmployeeWithPensionPlan) and make it inherit from the pure virtual type.
  3. Use "virtual ~Employee()" instead of "virtual ~Employee(void)" (using void explicitly in the parameter is a hold over from C and is out of vogue in most C++ communities as far as I'm aware).
  4. Use "const string&" instead of "const char*" for the name.

So, to clarify, my recommendation would be:

class Employee {
    public:
        virtual ~Employee() {}
        virtual double GetSalary() const = 0;
    protected:
        Employee() {}
};

class FullTimeEmployee : public Employee {
     // your concrete implementation goes here
};

class MockEmployee : public Employee {
    public:
        MockEmployee() {}
        virtual ~MockEmployee() {}
        // ... your mock method goes here ...
};

You've already suggested a possible answer, but let's spell out some options:

1) Make the base default-constructible. Easiest to do by providing default arguments:

explicit Employee(PensionPlan *pensionPlan = 0, const char * fullName = "");

(Note that we say explicit to avoid tacit conversions from PensionPlan*.)

2) Call the constructor in the derived class's constructor's base initializer list:

EmployeeFake::EmployeFake() : Employee(0, "") { }

2a) Give EmployeeFake an appropriate constructor and pass it on:

EmployeeFake::EmployeeFake(PensionPlan *p) : Employee(p, "[fake]") { } 

(Note that (1) is a declaration, while (2) and (2a) are the definitions.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!