Reputation: 319
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!
Upvotes: 0
Views: 82
Reputation: 15334
If foo
is just a handle or wrapper for a foo2
it might make sense to overload operator->
:
#include <iostream>
class foo2 {
public:
void method1(){ std::cout << "method1\n"; }
void method2(int /*arg2*/) { std::cout << "method2\n"; }
};
class foo {
foo2 myfoo2;
public:
foo2* operator->() { return &myfoo2; }
};
int main() {
foo f;
f->method1();
f->method2(1);
}
Upvotes: 1
Reputation: 2124
Why not have one method in your foo class that returns a pointer (or const pointer) to your foo2 class like so:
class foo
{
public:
foo2* getFoo2() const { return foo2_; }
private:
foo2* foo2_;
};
Then on the outside you can use it like so:
foo f;
auto f2 = f.getFoo2();
f2->method1();
f2->method2(/*args*/);
Upvotes: 0
Reputation: 5244
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;
};
Upvotes: 1