首页 > 解决方案 > Implementing virtual function without a derived class

问题描述

I want to know if this is an acceptable use of a class with a virtual function.

I have a game engine project that has this code:

std::unique_ptr<ComponentFactory> componentFactory = std::make_unique<ComponentFactory>();

auto component = std::static_pointer_cast<BrainComponent>(componentFactory->create(definitionJSON, ComponentTypes::BRAIN_COMPONENT));
addComponent(component, ComponentTypes::BRAIN_COMPONENT);

In this game engine project (which builds to a .lib), I have a ComponentFactory.h file with the create function as virtual.

// ComponentFactory.h

class ComponentFactory
{
public:

    virtual std::shared_ptr<Component> create(Json::Value definitionJSON, ComponentTypes componentType);

};

Separately, in my copterRescue project that uses my game engine .lib, I have the ComponentFactory.cpp defined. The ComponentFactory.cpp does not exist in the game engine project at all.

The copterRescue project includes the ComponentFactory.h from the game engine project.

The copterRescue project will not build unless an implementation of 'create" has been included (which is fine with me)

//ComponentFactory.cpp

#include "ComponentFactory.h"

std::shared_ptr<Component> ComponentFactory::create(Json::Value definitionJSON, ComponentTypes componentType)
{
   //Do stuff specific to this game to create and return a particular Component
}

In this way, I can have my "whatever" game create an overriding, game specific, component creating function that gets used within the game engine code. i.e. It allows me to inject game specific code while using my shared game engine library.

In the past, my classes with virtual functions were overriden by a derived class, and there's no derived class in this case, so is it considered bad practice?

标签: c++

解决方案


推荐阅读