why need pure virtual?

Started by
5 comments, last by nilkn 18 years, 7 months ago
I see only a reason for it: that is :forbid instantiate the class? there are other reason for pure virtual??
Advertisement
It's basically provides a basic structure, which many classes can derive from.
-----------------------------Play Stompy's Revenge! Now!
Its used to make pure abstract classes which act as a interface.
You are right - there is no need for it, only want.

You want it to make your program cleaner -- some functions have no meaningful body -- so show it!

Oxyd
Say there are two people working on a project. One person works on class A while the other works on Class B. The thing is that Class A needs Class B and vice versa. The lead programmer can then make an interface for both class a and b which the programmers must follow. The can then do whatever they want inside the child class aslong as they have the functions declared in the interface doing what they should. The other programmer can now just use the interface to create his class and use those functions when needed. This way, both programmers can be working at the same time without having to rely on each other.


Another place it can be used is when creating engines. The engine programmer can create an interface to a dll. This interface and a very bare bones engine which has no optimization etc, can be given to the programmers to work with. Once the engine is completed, the engine programmer just needs to hand the dll over to the game programmers and the game will automatically use the new improved engine without the need to recompile. Also usefull if they plan to create an engine which can use more than one api (DX, GL).

This way, the program can see which dll needs to be loaded and the corresponding dll will be loaded but the interface remains the same hence, no program code needs to change, Just the dll which is loaded.
______________________TradeMark Designs
It can also be useful if you are building a program (possibly a dll or an api) and you create the abstract class and a subclass for it. You can pass a pointer or reference to this class as a function call so that if someone wanted to change the functionality of the class it will be easy to do. all they need to do is make a child class and pass in the child.

~guyaton
~guyaton
Pure virtual functions allow the programmer to enforce their design.

If they intend for a class to be an abstract interface, it only makes sense to instantiate one of it's children. They can enforce these semantics by making the methods of the abstract interface pure virtual.

Like Oxyd said, there is no real "need" for pure virtual functions. It does, however, make the code cleaner, and what is doubly better, make the intentions of the programmer more evident.

guyaton: What you describe is sub-typed run-time polymorphism, and requires methods only to be virtual.

This topic is closed to new replies.

Advertisement