How to Use CRuntimeClass in Visual C++

By eHow Computers Editor

Rate: (0 Ratings)

In MFC programs, objects are created and destroyed based on the user's actions. This unpredictability makes it necessary to have a mechanism that provides dynamic runtime information about objects. This information includes the class name, extra type checking, inheritance from other classes and object creation based on a familiar name. The CRuntimeClass, which is analogous but more sophisticated than the typeid keyword of C++, does all this.

Instructions

Difficulty: Moderately Easy

Things You’ll Need:

  • Microsoft Visual Studio or .NET Studio IDE
  • MFC programming basics
  • MFC book, such as "Visual C++ Programmer's Guide" by Beck Zaratian
Step1
Prepare a simple MFC program (single document, multiple document or dialog based) involving several controls.
Step2
Associate a class with the CRuntimeClass class. Insert the DECLARE_DYNAMIC macro inside the class definition in the class header file. Add the IMPLEMENT_DYNAMIC macro at the top of the source file of the class. The macro takes two parameters: the class in question and CObject. Now that these formalities are finished, you can provide runtime information.
Step3
Get the name of the MFC class by using the m_lpszClassName member. It returns an LPCSTR, which is an ASCII null-terminated string containing the class name.
Step4
Find the size of the class using the m_nObjectSize member. It returns an int that is the size of the object in bytes. If members of the object point to allocated memory, that memory isn't included.
Step5
Create a specified class dynamically at runtime. You can do this by using the CreateObject() member, which returns a pointer to a CObject.
Step6
Determine whether a given class is derived from a certain base class. To do this, use the IsDerivedFrom() member, which takes as parameter the CRuntimeClass* structure of the base class. It ascends the inheritance chain and returns "true" if it finds a match.
Step7
Use the IsKindOf() member to do type checking. It accepts as parameter a pointer to the CRuntimeClass of the associated class. "True" is returned if the types match.

Tips & Warnings

  • The CRuntimeClass class contains more features than the ones mentioned in this article.
  • Don't use this tutorial as a programming guide but instead as a first step resource to get a brief exposure on the CRuntimeClass class.

Post a Comment

POST A COMMENT

Request a New How-To Article

Looking for more How To information? Chances are there’s an eHow member who knows how to do what you’re looking to do. Submit an article request now!

eHow Article: How to Use CRuntimeClass in Visual C++

eHow Computers Editor

eHow Computers Editor

Category: Computers

Articles: See my other articles

Related Ads