How do I pass this instance as a parameter into a function?
class
{
public:
void foo();
} bar;
Do I have to name the class?
It
Why should you create an anonymous class when you want to pass it to a function?
Just explicitly declare the class:
class Foo {
// ...
};
void Method(Foo instance);
int main() {
Foo bar;
Method(bar);
}
The 2nd possibility would be using a template-function, so the compiler would infer the type (Note that this is not standard-compatible!)
#include
using namespace std;
template
void SayFoo(T& arg) {
arg.Foo();
}
int main() {
class {
public:
void Foo() { cout << "Hi" << endl; }
} Bar;
Bar.Foo();
SayFoo(Bar);
return 0;
}
There is no problem with copying the class since the compiler generated the copy constructor automatically and you can use tools like boost::typeof in order to avoid referring to the type explicitly.
BOOST::AUTO(copy, Bar);
Another approch is using (relatively slow) runtime-polymorphism (interfaces/inheritance).