Consider following Java program:
abstract class Surprising
{
void fun()
{
System.out.println("fun() is invoked");
}
}
class myclass
{
public static void main(String args[])
{
Surprising s=new Surprising() { };
s.fun();
}
}
Here I am creating object of nameless subclass of my abstract class Surprising, not the object of abstract class because it isn't allowed to create object of abstract class in Java.
What is the equivalent C++ program? Is it possible to do this in C++? If yes, how & if no, why not allowed?
In C++ the Surprising
class would not be abstract, because it defines all of its members. If you want an abstract (i.e. not instantiable) class, make at least one of its members pure virtual. Like here:
class Surprising
{
public:
virtual void fun()=0;
};
You can then define the member in an anonymous class of which you create an instance and then invoke the newly defined member function on that instance:
#include <iostream>
int main()
{
class : public Surprising
{
public:
virtual void fun() { std::cout << "Surprise!" << std::endl; }
} inst_;
inst_.fun();
return 0;
}