Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pure virtual function vs. virtual function?

Tags:

c++

I'm developing a class with some functionality that I think might need to be extended later, but not now. If the class were to be extended, then I think this would make instantiating the base class meaningless.

For example, let's say my base class is a tree. One approach would be to just put everything that the tree needs to do for my purposes in the tree class and leave it at that. However, this tree might be useful in other aspects of the program later on in life, so I've thought about creating a pure virtual onNodeVisited function. Derived classes could then implement their own version of onNodeVisited, and not have to worry about the specifics of the tree traversal defined in the based class.

Does it make sense to not use a pure virtual function and keep the tree functionality and application-specific functionality in one class (virtual onNodeVisited)? Or, should I make the tree class abstract and implement one sub-class for the application-specific part.

like image 379
Zach Rattner Avatar asked Oct 11 '22 06:10

Zach Rattner


1 Answers

I wouldn't decide that now. Later you could make an abstract base class for Tree and move code there, if that made sense.

Another option to inheritance for this kind of thing is a pointer-to-function or functor type to call. It's a lot easier to reuse, because you don't have to keep making new classes for each new situation.

like image 110
Lou Franco Avatar answered Oct 26 '22 12:10

Lou Franco