Question

Let's say I'm writing an application which works with projects, 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?

Was it helpful?

Solution

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.

OTHER TIPS

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...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top