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

  • 25 June

    Convert Roman Number to Integer in Python

    Table of ContentsHow to Convert Roman Number to Integer in PythonHow to convert roman number to integer in python?Using the if...else statement to convert roman number to integer in Python.Using classes and a dictionary to convert roman number to integer in Python.Using the roman module to convert roman number to integer in Python.ConclusionWas this post […]

  • 11 June

    Remove Single Quotes from String in Python

    Table of ContentsRemove single quotes from string in Python.How to remove single quotes from string in Python?Using the replace() function to remove single quotes from string in Python.Using a for loop to remove single quotes from string in Python.Using the join() function to remove single quotes from string in Python.Using the re module functions to […]

  • 11 June

    Escape Backslash Character in Python

    Table of ContentsEscape backslash character in python.How to use escape backslash character in python?Using the escape backslash character in python to represent whitespace characters.Using the escape backslash character in python to turn special characters into ordinary characters.Using the escape backslash character in f-strings in Python.Using the escape backslash character in raw strings in Python.Was this […]

  • 11 June

    Remove Parentheses From String in Java

    Table of ContentsJava StringsRemove Parentheses From a String Using the replaceAll() MethodRemove Parentheses From a String by TraversingConclusionWas this post helpful? Java uses the Strings data structure to store the text data. This article discusses methods to remove parentheses from a String in Java. Java Strings Java Strings is a class that stores the text […]

  • 11 June

    Break out of function in Python

    Table of ContentsBreak out of function in PythonHow to break out of function in Python?Using the return statement to break out of function in PythonUsing the try and except block to break out of function in PythonUsing the sys.exit() function to break out of function in PythonConclusionWas this post helpful? In this post, we will […]

  • 11 June

    Check if Object Is Iterable in Python

    Table of ContentsWhat are iterables in Python?How to check if object is iterable in Python?Using the iter() function to check if object is iterable in PythonUsing the for loop to check if object is iterable in PythonUsing the isinstance() function to check if object is iterable in PythonConclusionWas this post helpful? In this post, we […]

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.