Implement abstract class as a local class? pros and cons

Posted by sinec on Stack Overflow See other posts from Stack Overflow or by sinec
Published on 2010-03-17T14:08:25Z Indexed on 2010/03/17 14:11 UTC
Read the original article Hit count: 160

Filed under:
|
|
|

Hi,

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 reason 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!

© Stack Overflow or respective owner

Related posts about c++

Related posts about local