tags:

views:

84

answers:

1

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

+5  A: 
  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.)

sbi
@sbi: it seems that it's time for me to take a rest as I couldn't remember unnamed namespaces:)p.s. thanks for the info that they can't be used as template arguments since I didn't know it!
sinec