开发者

Should downcasting be avoided while using a class hierarchy in C++?

开发者 https://www.devze.com 2023-02-03 09:50 出处:网络
Let\'s say I\'m writing an application which works with 开发者_如何学Pythonprojects, and exposes different functionality depending on the type of the project. I have a hierarchy of classes for the dif

Let's say I'm writing an application which works with 开发者_如何学Pythonprojects, and exposes different functionality depending on the type of the project. I have a hierarchy of classes for the different types of projects:

class AbstractProject
{
};

class ProjectA : public AbstractProject
{
};

class ProjectB : public AbstractProject
{
};

class ProjectC : public AbstractProject
{
};

Now, I was planning to have an AbstractProject *_currentProject pointer as a member in the application's main class, pop up a dialog box on startup and based on the selection, do:

_currentProject = new ProjectB(); // e.g.

Later, I'll have to downcast the pointer to the specific type to utilize the functionality specific to different Project-s. Somehow this makes me feel uneasy. Is there a Better Way of doing this?


Better way is to define pure virtual methods in base class and later implement all specific functionality in overloads in derived classes. Then call that method.


Yes you should use virtual methods instead, whenever possible.


The Command and the Visitor pattern may both apply here. You should decide for yourself which fits better for your case.

http://en.wikipedia.org/wiki/Command_pattern

http://en.wikipedia.org/wiki/Visitor_pattern


In pure OO, you should have virtual methods like everyone suggested. However, if you still need to go for specific member functions, try using one of the design pattern, may be command or visitor or even decorator...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号