- Virtual Functions
The function declared in the base class can be redefined in each derived class. For example
1: # Include<Iostream>
2: # Include<String>
3: Using NamespaceSTD;
4: ClassEmployee {
5:String first_name, family_name;
6:ShortDepartment;
7: Public:
8:Employee (ConstString & N,IntD );
9:Virtual VoidPrint ()Const;
10:};
11: VoidEmployee: Print ()Const{
12:Cout <family_name <Department <Endl;
13:}
14:Employee: employee (ConstString & N,IntD): first_name (N), Department (d ){}
15: ClassManager:PublicEmployee {
16:// List <employee *> group;
17:ShortLevel;
18: Public:
19:Manager (ConstString & N,IntD,IntLVL );
20:VoidPrint ()Const;
21:};
22:MANAGER: Manager (ConstString & N,IntD,IntLVL): employee (n, d), level (LVL ){}
23: VoidMANAGER: Print ()Const
24:{
25:Employee: Print ();
26:Cout <level <Endl;
27:}
28: IntMain ()
29:{
30:Employee E ("Brown", 1234 );
31:Manager M ("Smith", 1234,2 );
32:E. Print ();
33:M. Print ();
34:Employee * P = & E;
35:P-> Print ();
36:P = & M;
37:M. Print ();
38:Manager * q = & M;
39:Q-> Print ();
40:
41:}
The base class declares a virtual function virtual void print () const; used to print the information of class members. Define the specific content of the print function in the base class and the derived class respectively.
Define a pointer to the base class object in the implementation, and assign values to the base class and the object address of the derived class respectively. Then call the print function through the pointer. We can find that the print function defined by the base class and the derived class is called respectively.
Which of the following Derived classes does the indicated object belong? Through virtual functions, we solve this problem.ProgramThe output is:
1:1234
2:1234
3:2
4:1234
5:1234
6:2
7:1234
8:2