Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement abstract class as a local class? pros and cons

Tags:

c++

class

local

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:

  1. I'm lazy to implement class (B) in separate files
  2. MethodToOverride just delegates call to other class
  3. Class B shouldn't be visible to other users
  4. no need to worry about deleting aInst since smart pointers are used in real implementation

So my question is if I'm doing this right?

Thanks in advance!

like image 972
sinek Avatar asked Mar 17 '10 14:03

sinek


People also ask

Why should we use abstract class instead of normal class?

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.

What are the benefits of abstract class in C#?

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.

When should we go for abstract class?

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.


1 Answers

  1. You could define B in the unnamed namespace of the implementation file where you implement GetPtrToAImplementation().

  2. A should have a virtual dtor.

  3. 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.)

like image 95
sbi Avatar answered Sep 25 '22 19:09

sbi