Zach
Zach

Reputation: 537

A java-like class class in cpp

I want to write a program that supports several types of commands.
In order to make it generic and easy to extend for later new commands, i want to write a class for each command (with its own handling), and call the base 'command' class with the handler function.
I know that in Java there is the class class to help with such a thing - to decide 'on the flow' the type of the class it is dealing.
Does cpp has a similar mechanism? If so, what is it and how do i use it?
If not, what can i do in order to keep it easily extended?

Thanks a lot.

Upvotes: 1

Views: 123

Answers (3)

Andy Thomas
Andy Thomas

Reputation: 86411

Although you can use the Class class to decide flow in Java, it's better to use polymorphism - it makes the class open for extension without requiring modification (the "O" in SOLID).

The same is true in C++. You could use RTTI, but virtual methods allow you to extend the class using the commands without modifying it.

From "Design Patterns" by Gamma et al.:

The key to this pattern is an abstract Command class, which declares an interface for executing operations. In its simplest form this interface includes an abstract Execute operation.

Upvotes: 1

Blazes
Blazes

Reputation: 4779

You could implement a Command class with a pure virtual method.

http://www.exforsys.com/tutorials/c-plus-plus/c-pure-virtual-function-and-base-class.html

Upvotes: 1

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174309

You can use RTTI, but I suggest you find another way of doing it.

Upvotes: 0

Related Questions