Does any buddy tell me use of asterik in C++ ?? And also explain use of static in methods and in constructors. Actually I am search a code that dynamically creates an object of class.
Anyone please help !

class BoxFactory
{
  public:
    static Box *newBox(const std::string &description)  //expalin this line of code please
    {
      if (description == "pretty big box")
        return new PrettyBigBox;
      if (description == "small box")
        return new SmallBox;
      return 0;
    }
};

In this case the asterisk indicates that the variable returned by the function is a pointer. Google "C++ pointer" for more informaiton. Basically, it indicates a memory address where information of some sort can be found.

A static member function is one that can be called without needing an instance of the class to call it on. So, in this case, you would do something like:

Box* b = BoxFactory::newBox( "small box" );

If the method wasn't static, you'd need to do:

BoxFactory bf;
Box* b = bf.newBox( "small box" );

As well as being more lines of code, you've also had to create a new object on the stack, and that takes time and resources so you don't want to do it if you don't have to.

A further note on this example is that it's not considered exception-safe ( Google "C++ exception safety" ) to return raw pointers from factory functions like this - you should use a smart pointer of some kind:

class BoxFactory
{
  public:
    static std::auto_ptr< Box > newBox(const std::string &description)
    {
      if (description == "pretty big box")
        return std::auto_ptr< PrettyBigBox >( new PrettyBigBox );
      if (description == "small box")
        return std::auto_ptr< SmallBox >( new SmallBox );
      return 0;
    }
};

Then, when you use the newBox function:

std::auto_ptr< Box > ptrBox = BoxFactory::newBox( "small box" );

Google "C++ smart pointer" if you've never seen this kind of thing before. There are lots of smart pointers (and std::auto_ptr isn't the best one, but it is the most widely supported on older compilers). If you have a newer compiler you should use std::unique_ptr or std::shared_ptr, of if you have the boost libraries available, boost::shared_ptr.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.