Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a good code (came across while reading code of a colleague)

Tags:

c++

File a.hpp:

class a;
typedef boost::shared_ptr<a> aPtr

class a{
public:
    static aPtr CreateImp();
    virtual void Foo() = 0 ;
    ....
};

File aImp.hpp:

class aImp : public a{

    virtual void Foo();

};

File aImp.cpp:

aPtr a::CreateImp()
{
     return aPtr(new aImp());
}

void aImp::Foo(){}

The client must use CreateImp to get pointer to a, and can't use a other ways. What do you think about this implementation? What do you think about this kind of implementation?

like image 864
amitlicht Avatar asked Mar 21 '10 20:03

amitlicht


1 Answers

This looks like a normal implementation if the Factory Method design pattern. The return of boost::shared_ptr just makes life of the programmer using this API easier in terms of memory management and exception safety and guards against simple mistakes like calling the function and ignoring the return value.

Edit:

If this is the only implementation of the base class, then it might be that the author was aiming for pimpl idiom to hide the implementation details and/or reduce compile-time dependencies.

like image 128
Nikolai Fetissov Avatar answered Sep 23 '22 13:09

Nikolai Fetissov