Running type information (RTTI) in C ++ and dynamic forced type conversion

Source: Internet
Author: User

If you want to modify the information of the corresponding derived class object at runtime when using general programming (that is, polymorphism), we can use the powerful runtime type information mechanism in C ++, to change the object state of the corresponding derived class. Next, we will dynamically change the state of the BaseCommsionEmployee object, and dynamically increase its basic salary by 10% during the running of the program. And dynamically print the type information of the derived class object referred to by the base class Employee pointer.


Example code

# Include <iostream>
# Include <string>
# Include <vector> // container header file in the standard library
# Include <iomanip> // stream format settings
# Include <typeinfo> // Object Type Recognition typeid Function Definition
# Include "Employee. h" // header file of the Employee abstract class
# Include "BaseCommsionEmployee. h" // employees with salaries and gold are charged by a certain percentage of the products sold, that is, the Commission.
# Include "CommsionEmployee. h" // only employees with gold are allowed.
# Include "HourlyEmployee. h" // hourly employees are billed on an hourly basis.
# Include "WeekEmployee. h" // weekly salary for employees with fixed weekly salary


Using namespace std; // all global variables and functions in the namespace std
Void ptrPrint (const Employee const *); // print the function prototype of the corresponding information and receive a constant pointer to the constant Employee object

// The real parameter status that enters the function will not be changed by the called Function

Int main (){
Vector <Employee *> employee (4); // declare a Vector container object that contains an array containing four Employee * pointers
Employee [0] = new CommsionEmployee ("bai", "sunwu", "123456789", 0.5, 10000 );
Employee [1] = new BaseCommsionEmployee ("bai", "ruru", "987654321", 0.5, 10000,300 0); // dynamically apply for a baseCommsionEmployee object
Employee [2] = new WeekEmployee ("bai", "sun", "192837465", 4000 );
Employee [3] = new HourlyEmployee ("bai", "wu", "00000000", 8,100); // the pointer of the corresponding object is returned for the new keyword.
Cout <setprecision (2) <fixed <endl; // stream output format definition. The output of all values retains two valid values and is rounded

// This format is highly passed and works for the output of all the values below
For (size_t j = 0; j <4; j ++ ){

// The following statement dynamically determines whether the base class Pointer Points to the derived class object is of the corresponding BaseCommsionEmployee type,

// If yes, the base class pointer is forcibly converted down to the pointer of the derived class and assigned to the basePtr pointer variable.

// Call the method that only belongs to the derived class object to modify the state of the derived class Object (that is, the base salary of the BaseCommsionEmployee object increases by 10%

// If the base class pointer is not a BaseCommsionEmployee object, the value of basePtr is 0.
BaseCommsionEmployee * basePtr = dynamic_cast <BaseCommsionEmployee *> (employee [j]);
If (basePtr! = 0) {// determine whether it is a BaseCommsionEmployee object
Cout <"Old baseCommsionEmployee sala =" <basePtr-> getBaseSalary () <endl;
BasePtr-> setBaseSalary (1.1 * basePtr-> getBaseSalary ());
Cout <"After increame 10%, Now baseCommsionEmployee baseSala =" <basePtr-> getBaseSalary () <endl;
}
Employee [j]-> print (); // The method of printing the derived class object referred to by the base class pointer of polymorphism. Note that this method must be a visual method.
Cout <"\ nEarning =" <employee [j]-> earning () <endl;
}

For (size_t I = 0; I <4; I ++) {// checks the type information of the derived class object referred to by the base class for polymorphism, and prints

// The typeid function is defined in the typeinfo header file. typeid () receives a type object. This function returns a typeinfo object and calls the name method of the typeinfo object, that is, you can print the specific type information of the input type object.
Cout <"Now Object =" <typeid (* employee [I]). name () <"is destrctor !!! "<Endl; // return the corresponding typeinfo object
Delete employee [I]; // dynamically releases the corresponding memory.
}
}

Void ptrPrint (const Employee const * employee) {// constant pointer to constant data
Employee-> print ();
Cout <"\ nearning =" <employee-> earning () <endl; // call all methods statically: employee-> earning ();
}

========================================================== ==========

Program Execution result:

CommsionEmployee: bai, sunwu
SocialNumber: 123456789 SalaryRate = 0.50, sailSalary = 10000.00
Earning = 5000.00.
Old baseCommsionEmployee sala = 10000.00 // The BaseCommsionEmployee object type is dynamically recognized here, the forced type conversion is dynamically performed, and the corresponding information is modified.
After increame 10%, Now baseCommsionEmployee baseSala = 11000.00
BaseSalary CommsionEmployee: bai, ruru
SocialNumber: 987654321 SalaryRate = 0.50, sailSalary = 10000.00 BaseSalar
1000.00
Earning = 16000.00.
WeekEmployee: bai, sun
SocialNumber: 192837465 weekSalary = 4000.00
Earning = 4000.00.
HourEmployee: bai, wu
SocialNumber: 00000000 hours = 8.00 hourSalary = 100.00
Earning = 800.00.
Now Object = class CommsionEmployeeis destrctor !!! // Dynamic Type Recognition
Now Object = class BaseCommsionEmployeeis destrctor !!!
Now Object = class WeekEmployeeis destrctor !!!
Now Object = class HourlyEmployeeis destrctor !!!

 


 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.