How to know the type of object a pointer points to in C++? -


Suppose I have defined two classes based on a basic class:

  Class Basic {public: int i; }; Class DeriveA: Public Basic {Public: int j; }; Category DerivedB: Public Basic {Public: int k; }; After that, a collection is now named class, in which  original  class 

  class Collect {public: Basic * PBASIC; Running zero (); };  

In this class, a function is defined as run () , which will indicate some operation based on the type of object:

< Pre> zero gather :: run () (if (pBasic points to derivedA object) {} (pBasic points to DerivedB object) {}}

then my question is as follows Is:

  • With C ++, is it possible to know the type of object of the type of indicator type?
  • Is there something different to vary depending on the type of object good Is the food, as illustrated in the run function?

Basic should be at least one virtual member since you want to create a range hierarchy, so I have to ensure that the ~ Basic virtualization will be at the same time.

The reason behind this is that a virtual member, you copy the class When each object is forced to engage the pointer of a specific type, which is that implementation could then use to your inquiry.

  class Basic {public: int i; Virtual ~ Basic () {}}; Class DeriveA: Public Basic {Public: int j; }; Class DerivedB: Public Basic {Public: int k; };  

You can now write your check:

  Zero Archive :: Run () {If (DerivedA * pDerived = dynamic_cast & lt; DerivedA * Gt; (pBasic) {} if (DerivedB * pDerived = dynamic_cast & gt; DerivedB *> (pesticide)) {}};   

Dynamic_cast will return a nullptr if it fails, you will only enter the body When your cast is successful and pdevard is a valid indicator for the exact derived object.


Comments

Popular posts from this blog

import - Python ImportError: No module named wmi -

Editing Python Class in Shell and SQLAlchemy -

lua - HowTo create a fuel bar -