Type recognition in C + +

Source: Internet
Author: User

base class pointer to child class object

The base class reference becomes the alias of the Child class object

Static type-the type of the variable (object) itself

Dynamic type-The actual type of the object to which the pointer (reference) points

Whether a base-class pointer can force a type to be cast to a child-class pointer depends on the dynamic type!

How do you get dynamic types in C + +?

Solutions-Leveraging Polymorphic

1. Define a virtual function in the base class to return specific type information

2. All derived classes must implement the associated virtual function

3. The type virtual functions in each class require a different implementation

Defects in polymorphic Solutions

Type virtual functions must be provided starting from the base class

All derived classes must override the type virtual function

The type name of each derived class must be unique

C + + provides the typeID keyword for obtaining type information

typeID keyword returns the type information for the corresponding parameter

typeID returns a Type_info class object

Throws an exception when the typeID argument is null

Use of typeID keywords

Int i = 0;

Const type_info& Tiv = typeID (i);

Const type_info& tii = typeid (int);

typeID precautions

When a parameter is a type: returns static type information

When the argument is a variable:

No virtual function table-returns static type information

Virtual function table exists-returns dynamic type information

Summary

The concept of static types and dynamic types in C + +

Using polymorphism to realize dynamic type recognition of objects

typeID is a keyword that is specific to type recognition

typeID ability to return dynamic type information for an object

Type recognition in C + +

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.