In Java, if I have an interface, I can do something like this:
blah.setOnClickListner(new OnClickListner() {
public void clicked() { // do something }
}
Can I do something similar in C++?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
C++ supports local classes. The syntax is the same as for any class type, except that member functions and static member variables must be defined inside the class body, not declared and defined later (there’s no way to name the member from outside the enclosing function).
Beginning in C++11, they can be used as template type parameters, which makes them much much more useful.
It would look something like:
(but watch out for leaks)
C++ tends not to use interfaces for this, though. A better design is to accept a functor for the listener, which in C++11 allows the use of lambdas (the compiler creates the local class for you).