Or simply put
can I do some thing like
class A {
public:
virtual void foo() = 0;
};
class B {
public:
A *a;
b(){
a = new A() { vo
No, C++ doesn't have anonymous classes like Java's.
You can define local classes, like this:
class B {
public:
A *a;
b(){
struct my_little_class : public A {
void foo() {printf("hello");}
};
a = new my_little_class();
}
};
Or maybe just a nested class:
class B {
private:
struct my_little_class : public A {
void foo() {printf("hello");}
};
public:
A *a;
b(){
a = new my_little_class();
}
};
In C++03, local classes have some limitations (for example, they can't be used as template parameters) that were lifted in C++11.
In Java, anonymous classes are sometimes used to do what other languages do with anonymous functions like, for example, when you create an anonymous implementation of Runnable
. C++11 has anonymous functions (also known as lambdas), so that could be an option if this is what you're trying to achieve.