Search code examples
c++classcall

"Pass" function call from class to class, C++


Is there a way to pass a function call from class to class? For example:

//foo.cpp
foo::foo
{
  ...
  myfoo2 = new foo2();
  ...
}

//foo2.h
class foo2
{
  ...
  public:
  void method1();
  void method2(int arg2)
  ...
}

Now I want to use the method of foo2 (eg method2) from outside of the foo class without having to implement the following:

//foo.cpp
...
void foo::method2(int arg2)
{
  myfoo2->method2(arg2);
}

The problem is, that i have quite a lot of these, and this would take a lot of space and does not look nice. Is there any other solution, or at lest a short version with the same effect?

Thank you in advance!


Solution

  • You can use private inheritance to include a foo2 object in your foo class, without creating an is-a relationship. Then you can simply expose the function with a using statement, like so:

    class foo : private foo2
    {
    public:
        using foo2::method2;
    };