Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7960237
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T04:41:56+00:00 2026-06-04T04:41:56+00:00

I am using the factory pattern. It basically allows classes to be registered at

  • 0

I am using the factory pattern. It basically allows classes to be registered at compile time and stored in a map. An instance can then be returned using BaseFactory::createInstance()

I am not sure how a map is holding class names at compile time !! How can memory be allocated in compile time that’s valid at run time ?

All class is in this case is derived from the parent class Bump_BaseObject

//C++ STL used for adding Reflection
#include <string>
#include <map>


class Bump_BaseObject;

/**
 * Derived Base objects creation factory
 */
template<typename T>
Bump_BaseObject* createT(void)
{
#pragma message("createT instantiated")
    return new T();
}

struct BaseFactory {
    typedef std::map<std::string, Bump_BaseObject*(*)()> map_type;

    //return an instance of the class type 's'
    static Bump_BaseObject* createInstance(const std::string& s) {
        map_type::iterator it = getMap()->find(s);
        if(it == getMap()->end())
            return 0;

        //this is where we instatiate and allocate memory for the object(it must NOT have any arguments)
        //we could write a variant that accepts args, but there is no need.
        return it->second();
    }

    //check if 's' is present in the map of registered types
    static bool checkIfRegisteredType(const std::string& s) {
        map_type::iterator it = getMap()->find(s);
        if(it == getMap()->end())
            return false;

        return true;
    }

protected:
    static map_type* getMap() {
        // never delete'ed. (exist until program termination)
        // because we can't guarantee correct destruction order
        if(!objectMap) { objectMap = new map_type; }
        return objectMap;
    }

private:
    static map_type * objectMap;
};

#define VALUE_TO_STRING(x) #x

template<typename T>
struct DerivedRegister : BaseFactory {
    DerivedRegister(const std::string& s) {


#pragma message("Type registered")
        getMap()->insert(std::pair<std::string, Bump_BaseObject*(*)()>(s, &createT<T>));
    }
};

Also is there a way to print the class names as they get registered ?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T04:41:57+00:00Added an answer on June 4, 2026 at 4:41 am

    I think your code is altogether confused, mixing preprocessor directives with strange inheritance patterns. Instead of trying to fix it, I’d like to present a generic, self-registering factory framework (which will print out registrations as they happen).

    Note that all global initialization happens during the dynamic initialization phase, i.e. at runtime just before main() is called.

    Base.hpp:

    #include <unordered_map>
    #include <string>
    
    class Base
    {
    public:
        typedef Base * (*base_creator_fn)();
        typedef std::unordered_map<std::string, base_creator_fn> registry_map;
    
        virtual ~Base() = default;
    
        static registry_map & registry();
        static Base * instantiate(std::string const & name);
    };
    
    struct Registrar
    {
        Registrar(std::string name, Base::base_creator_fn func);
    };
    

    Base.cpp:

    #include "Base.hpp"
    #include <iostream>
    
    registry_map & Base::registry()
    {
        static registry_map impl;
        return impl;
    }
    
    Base * Base::instantiate(std::string const & name)
    {
        auto it = Base::registry().find(name);
        return it == Base::registry().end() ? nullptr : (it->second)();
    }
    
    Registrar::Registrar(std::string name, Base::base_creator_fn func)
    {
        Base::registry()[name] = func;
        std::cout << "Registering class '" << name << "'\n";
    }
    

    Usage Example

    Example.hpp:

    #include "Base.hpp"
    
    class DerivedExample : public Base
    {
        static Registrar registrar;
    public:
        static Base * create() { return new DerivedExample; }
        // ...
    };
    

    Example.cpp:

    #include "Example.hpp"
    
    Registrar DerivedExample::registrar("DerivedExample", DerivedExample::create);
    

    Main.cpp

    #include "Example.hpp"
    
    int main()
    {
        Base * p = Base::instantiate("DerivedExample");
        Base * q = Base::instantiate("AnotherExample");
    }
    

    The crux here is that each derived class has a static Registrar member, which gets initialized (in unspecified order) during the dynamic initialization phase of your program, and each constructor of which performs the actual insertion into the registry map, as well as printing out of the log message.

    (If you don’t have a modern C++ compiler, you would have to use the old C++98-style syntax:)

    virtual ~Base() { }   //  no "= default"
    
    Base::registry_map::const_iterator it = Base::registry().find(name); // no "auto"
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Please help me how can I skip these conditions? I am using factory pattern.
I'm using the Factory pattern to hide some instance creation complexity. I have this:
I'm using the Ninject Factory Extension and creating a custom instance provider explained in
I have a task to perform an HttpWebRequest using Task<WebResponse>.Factory.FromAsync(req.BeginGetRespone, req.EndGetResponse) which can obviously
I am using Factory pattern to create .NET objects of a class. I also
Can anyone point me to a reference on how to implement the factory pattern
I currently have some DAOs set up using the abstract factory pattern. It looks
I was working with java code that is supposedly using the Factory pattern, but
How the factory pattern is using inheritance and abstract factory using composition to return
When you're using a factory pattern, how do you inject dependencies into constructors at

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.