Get Type of Object in C++

C++ is an object-oriented language where we often interact with objects of different types. The object interaction becomes more interesting when we add runtime polymorphism to it.

The runtime polymorphism, also known as, dynamic dispatch of methods, or method overriding means that a class can override the implementation of a method defined in the parent class. Since we can assign a child class’s reference to a parent object, it becomes complex to understand which method will be called. Moreover, in such cases, we might want to know the type of object.

For example, if we pass an object to a method, we might want to check its type so that logical errors and unwanted errors can be avoided. In this article, we will understand the logic behind method calling in runtime polymorphism, and then we will see how we can get the type of object in C++. 

Why Should We Determine the Type of Object in C++: Dynamic Dispatching

C++ supports runtime polymorphism or dynamic dispatch in form of method overriding. Due to this, it becomes important to understand the pattern of method calling in case of method overriding. As we know, when a class inherits from another class or classes, it inherits its non-private data and methods. The methods that are declared as virtual in the base class or parent class can be overridden in the child class. 

Another point to be noted is that a parent class object can store the instance of the child class. When we store the instance of the child class in the parent class, we can call all the methods that are defined in the parent class.

If a method is overridden in the child class, the instance of the method as defined in the child class will be called. We will understand the concept with an example. Note that we can not store a parent’s reference in the child’s object.

Let us take an example of two classes.

  • Let A is a class that has a virtual method fun() and a non-virtual method funA().
  • Let B is another class that inherits from A. Class B also has a non-virtual method funB(). Class B overrides the virtual method fun() with its own implementation. 
  • Now, let us say we create an object of class A (obj) and store in it a reference of class B.
  • When we call the obj.fun() method, the implementation of the fun() in class B is called.
  • If we want to call the method funB(), it will be an error because the funB() method does not exist in class A. However, we can call the funA() method using the ‘obj’ as well because it has been defined in class A.

Therefore, we can conclude that using the ‘obj’, we can call all those methods that have been defined in class A and if a method is overridden in class B, then for such a method, class B’s implementation will be executed. 

Let us understand the above example with the help of the following code. 

Output:

Since class A’s pointer ‘obj’ holds the instance of class B’s object, class B’s implementation of the method fun() is called in the above example. Other outputs are as usual. 

Get Type of Object in C++

We have now understood why it is important to determine the type of object while working with classes in C++. Another example where the type of object plays an important role is in the method calling. When we pass an object to a method, it might be needed to know the type of object to avoid unwanted erroneous output. 

C++ provides an operator called ‘typeid()’ operator for determining the type of object. The typeid() operator is defined as an operator that is used where the dynamic type of a polymorphic object must be known for static type identification.

Note that we should include the <typeinfo> before using the typeid() in our program. Moreover, the typeid() operator is an lvalue expression that means it identifies the location of the object. We can compare the results returned by the ‘typeid()’ operator.

The typeid() operator has a method ‘name()’ that returns the name of the class (or struct or the datatype) of which the object is passed to the typeid() operator. Note that we can compare the values returned by the typeid() operator.  If the typeid() operator is used with polymorphic objects, it causes a runtime overhead. Therefore, it should be used cautiously.

Let us understand the concept with code.

Output:

Note that the name of the class to which is object belongs is displayed but preceded by a number. This number represents the number of characters in the name of the class. We have also compared the results returned by the typeid() operator. Since the ‘objA’ and ‘objB’ hold the same reference of the object, we get the result of the comparison as true.  

Conclusion

Sometimes, especially working with dynamic polymorphism, we want to determine the type of object. It helps us to eradicate unwanted errors from the program. It also helps to avoid the erroneous outputs of the program.

Knowing the object type is mostly associated with the object of classes, structs, and unions. However, there is no restriction that can not pass the objects of primitive data types to the typeid() operator. 

The typeid() operator helps us to compare the two object types. It also has a ‘name()’ method that returns the name of the object passed to the typeid() operator. The typeid() operator comes in handy with parameter passing.

We have learned about dynamic dispatch which is necessary to understand the usefulness of the typeid() operator. We have then understood the typeid() operator, its uses, and its ‘name()’ method. The code demonstrates its use in practical programming. 

Hope you have enjoyed the article. Stay tuned for such articles. Happy Learning!

Was this post helpful?

Related Posts

  • 01 February

    Write Binary Files in PowerShell

    Table of ContentsUsing Add-Content CmdletUsing the [IO.File]::WriteAllBytes() MethodUsing FromBase64CharArray() with Add-Content Using Add-Content Cmdlet Use the Add-Content cmdlet to write binary files in PowerShell. [crayon-63da6ed93350b819769767/] This script created a new file named test.bin in the current working directory and wrote the binary data to the file. The script will overwrite the existing file with the […]

  • 01 February

    What Does Percent(%) Mean in PowerShell

    Table of ContentsUsing Percent (%) in Different ContextsUse Percent(%) as an alias of the ForEach-Object cmdlet in PowerShellUse percent (%) as the Modulus Operator in PowerShellUse percent(%) as an assignment operator (%=) in PowerShell Using Percent (%) in Different Contexts Typically the % character is for mod functionality. But in PowerShell, it’s an alias for […]

  • 28 January

    PowerShell – Get Number of Lines in CSV File

    Table of ContentsUsing Get-Content CmdletUsing Import-Csv CmdletUsing Get-ChildItem with Foreach-Object Using Get-Content Cmdlet The Get-Content cmdlet can be used in the following ways to get the number of lines in the specified .csv file: Get-Content cmdlet with .Length property Get-Content cmdlet with .Count property Get-Content cmdlet with .ReadCount property Get-Content cmdlet with Measure-Object cmdlet and […]

  • Read CSV file in PowerShell
    28 January

    Read CSV File in PowerShell

    Table of ContentsUsing the Import-Csv CmdletUsing the ConvertFrom-Csv CmdletUse the ConvertFrom-Csv Cmdlet with the Pipe (|) OperatorUse the ConvertFrom-Csv Cmdlet with the -InputObject Parameter Using the Import-Csv Cmdlet To read a CSV file in PowerShell, use the Import-Csv cmdlet. [crayon-63da6ed9348da443376082/] [crayon-63da6ed9348df590543255/] PowerShell provides several cmdlets that allow us to work with CSV files: Import-Csv ConvertFrom-Csv […]

  • Read File into String in PowerShell
    27 January

    Read File into String in PowerShell

    Table of ContentsUsing the Get-Content CmdletUse the Get-Content Cmdlet to Read a Single FileUse the Get-Content Cmdlet with forreach loop to Read Multiple FilesUsing [System.IO.File]::ReadAllText() MethodUse the [System.IO.File]::ReadAllText() Method with foreach loop to Read Multiple FilesUsing the Variable Notation with the Out-String Cmdlet Using the Get-Content Cmdlet We can use the Get-Content cmdlet to read […]

  • Get String between two characters in JavaScript
    27 January

    Get String Between Two Characters in JavaScript

    Table of ContentsUsing substring() MethodUsing slice() MethodUsing split() MethodUsing substr() Method 💡TL;DR Use the substring() method to get String between two characters in JavaScript. [crayon-63da6ed935536828168165/] [crayon-63da6ed93553c151582493/] Here, we got String between , and ! in above example. Using substring() Method Use the substring() method to extract a substring that is between two specific characters from […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.