If a class can be inherited, should each function be virtual?

In C ++, an encoder does not know whether other encoders inherit its class. Should it make every function in this class virtual? Are there any disadvantages? Or is it simply unacceptable?

+5
source share
7 answers

In C ++, you should only make a class inheritable if you plan to use it polymorphically. The way you handle polymorphic objects in C ++ is very different from how you relate to other objects. You are not inclined to put polymorphic classes on the stack or pass them or return them from functions by value, as this can lead to cutting . Polymorphic objects are usually distributed in heaps, passed and returned by a pointer or link, etc.

If you create a class that does not inherit and does not inherit from it, you cause all kinds of problems. If the destructor is not marked virtual, you cannot delete the object using the base class pointer without causing undefined behavior. Without member functions marked virtual, they cannot be overridden in a derived class.

, ++, , , . , virtual virtual. , . , , , - . , , , .

+10

++ . . , ++.

+4

, .

-. . , , , , / .

, , . , , , , .

+4

, , . , .

, , , , . , . , , , , , , , , , . , .

+2

.

, MFC ( 1990- ) . , MFC , . .

, , + 1 "", - . , , . , , ( ), ; , .

, .

, , , ( ) .

hth.,

+2

, , , . , , , . , , public.

, , . , , . protected, .

. (google ) , . , , , / . .

, virtual : . , . , .

+1

, , .

  1 > , , , .   2 > .   3 > - .

0
source

All Articles