1

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?

neuviemeporte
  • 6,310
  • 10
  • 49
  • 78

4 Answers4

2

Yes you should use virtual methods instead, whenever possible.

Šimon Tóth
  • 35,456
  • 20
  • 106
  • 151
2

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.

Andrey
  • 59,039
  • 12
  • 119
  • 163
  • Okay, just to clear up: I should still store a pointer to the base class initialized as a proper subclass, right? – neuviemeporte Jan 11 '11 at 13:17
  • @neuviemeporte yes. You have pointer to base class, but when you call method it will be dispatched to specific class. – Andrey Jan 11 '11 at 14:07
1

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

Markus Kull
  • 1,471
  • 13
  • 16
  • 1
    Visitor Pattern: Not really. Command Pattern. Maybe. More likely that a set of simple virtual methods will suffice. – Martin York Jan 11 '11 at 14:42
0

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

Vivek Madani
  • 287
  • 2
  • 11