Search code examples
c++testinggooglemock

Initializer list with more than initialization value


I have code like this:

#include <gmock/gmock.h>

class Example {

    Example(): d_variable1(somefunction1), d_variable2(d_variable1, "someString"), d_variable3(somefunction2) {

    }
   

    type1 d_variable1;
    type2 d_variable2;
    type3 d_variable3;

};

The part I don't get is: d_variable2(d_variable1, "someString"),

  • what is the purpose of someString as a 2nd "argument"?
  • is it even an "argument" or does it have a different name?

There's no compilation error so it is valid C++. All this code is in a test/mock file so I don't have actual values to test on. I have to correct/extend this test. I am learning to test but from what I understand, I have to determine what the behavior should be for a mock. I am also trying to understand the source code from the tests. They say that tests are good documentation but reading them now isn't clarifying things so I am starting to ask questions about the small bits of the code.


Solution

  • Let's say there is a class Foo which need not be defined by you:

    class Foo {
    public:
        Foo(int a, const char* b)
        {
            //...code
        }
    };
    

    Foo's constructor accepts 2 arguments. So, when constructing an object of Foo, you need to pass two arguments like this: Foo(5, "something").

    Now, let's say that your type2 is Foo (and type1 & type3 are int).
    Then your class Example could look like this:

    class Example {
        Example(): d_variable1(5), d_variable2(d_variable1, "someString"), d_variable3(46) {
    
        }
    
        int d_variable1;
        Foo d_variable2;
        int d_variable3;
    
    };
    

    d_variable2 is an object of Foo, so when you construct it, it can accept two arguments, which are d_variable1 and "someString". That is because the sole constructor of Foo accepts two arguments. And when you have more than one argument, it is still referred to as arguments.

    And my example of Foo does not even need to be a class you define. It could be any class; one that could even be part of STL.