for some reason I'm thinking on implementing interface within a some function(method) as local class.
Consider following:
class A{
public:
virtual void MethodToOverride() = 0;
};
A * GetPtrToAImplementation(){
class B : public A {
public:
B(){}
~B(){}
void MethodToOverride() {
//do something
}
};
return static_cast<A *>(new B());
}
int _tmain(int argc, _TCHAR* argv[])
{
A * aInst = GetPtrToAImplementation();
aInst->MethodToOverride();
delete aInst;
return 0;
}
the reasons why I'm doing this are:
So my question is if I'm doing this right?
Thanks in advance!
The short answer: An abstract class allows you to create functionality that subclasses can implement or override. An interface only allows you to define functionality, not implement it. And whereas a class can extend only one abstract class, it can take advantage of multiple interfaces.
The abstract keyword enables you to create classes and class members that are incomplete and must be implemented in a derived class. The sealed keyword enables you to prevent the inheritance of a class or certain class members that were previously marked virtual.
An abstract class is a good choice if we are using the inheritance concept since it provides a common base class implementation to derived classes. An abstract class is also good if we want to declare non-public members. In an interface, all methods must be public.
You could define B
in the unnamed namespace of the implementation file where you implement GetPtrToAImplementation()
.
A
should have a virtual dtor.
By the current C++ standard, you cannot use local classes as template arguments. (Which means you can't use them with the STL, for example.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With