1

I am using a similar code based on the following example:

class FOO
{
private:
    operator int() const;
};

class BARMOCK
{
public:
    MOCK_METHOD1(Bar, void(const FOO& foo));
};

Unfortunately the following error message is generated by the compiler:

gtest/internal/gtest-internal.h(892): error C2248: 'FOO::operator int': cannot access private member declared in class 'FOO'

which comes from gtest-internal itself:

static const bool value = sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1;

Is there any possible way to make it work, or is it a known limitation of the google mock framework?

Of course there are ways to workaround the problem, like:

class BARMOCK
{
public:
    MOCK_METHOD1(BarMock, void());
    void Bar(const FOO& foo) { BarMock(); }
};

But this is just a workaround, not a real solution. Does anyone know anything about this? Thanks.

273K
  • 29,503
  • 10
  • 41
  • 64
Iburidu
  • 450
  • 2
  • 5
  • 15

1 Answers1

0

The problem is that googlemock wants to print your FOO values. And it behaves according to this algorithm:

  1. If you have defined function PrintTo(FOO const&, std::ostream*) then it is used
  2. Otherwise, if it is possible to print via classic C++ way (with operator <<) then it is used
  3. Otherwise, the bytes that represents this FOO object are printed

In your case C++ compiler (not googlemock) is "fooled" by your private int cast operator - int is printable - so std::cout << FOO{} is printable - but - then compiler notices that this conversion is private...

So:

  1. Either defined PrintTo(FOO const&, std::ostream*)
  2. Or define std::ostream& operator << (std::ostream&, const FOO&) - this operator might be defined as friend function,

like:

class FOO {
  friend std::ostream& operator << (std::ostream& os, const FOO& foo)
  {
      return os << static_cast<int>(foo);
  }
PiotrNycz
  • 23,099
  • 7
  • 66
  • 112