简体   繁体   中英

Question about Pure Virtual Functions in C++?

I am reading some C++ text regrading Pure Virtual Functions. As the text says, the form of Pure Virtual Functions declaration, for example, is:

virtual void virtualfunctioname() = 0;

And the text explains: "Since pure virtual function has no body, the programmer must add the notation =0 for declaration of the pure virtual function in the base class."

I have tried to remove = 0; , that means I only declared virtual void virtualfunctioname(); and things worked fine.

So, why do we need to assign a 0 to the virtual function? Thanks

If a class has any pure virtual functions, it cannot be instantiated. Also, it forces any derived classes to implement those functions, otherwise they too cannot be instantiated.

So if you remove the = 0 , you'll just have a normal base class, which may be instantiated, and doesn't enforce an interface on its derived classes. You'll only get into trouble if you instantiate a base-class object (or a derived-class object with no override), and then try to invoke virtualfunctionname() on it, because there's no definition for it, so the linker will complain.

[Note, also the claim that "pure virtual functions have no body" is incorrect; you may define an implementation for a pure virtual. The class will still be abstract, though.]

If you don't declare a method as pure virtual, the compiler will assume there is an implementation of it somewhere. If you never instantiate the class that is supposed to contain those pure virtual (and abstract class to use the right terminology), you will be fine. However, if you do, the compiler will accept the code as valid and you will get a linker error later.

If you mark a method as pure virtual, the class containing it will be marked as abstract and the compiler will refuse any attempts to instantiate it.

When you declare a function as pure virtual function that class which contain it will known as abstract class and no instance would be created. Again no instance of that class would be created.This class is used for inheritance and the derived class must implement this method. otherwise compilation error will appear. Thanks

things worked fine

I assume you meant that the code compiled and linked. However, you probably haven't defined an implementation for virtualfunctionname in the base class you declare it, so if you ever do call the base implementation you will get a linker error.

At the moment things probably work because you provide an implementation in a derived class and use that instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM