C++: How do I access Form1 from Form2 and vice-versa?

At first glance, this seems like an easy task. All you want to do is access a member variable or control from Form1 on Form2, and do the same from Form2 on Form1. Unfortunately, this is not the easiest thing to do, at least in (Managed) C++.

Background
In a number of languages — such as Visual Basic, C#, and Java — it is very common (and easy) to access members from different Forms. In these languages it isn’t necessary to use headers per se, therefore most programmers find no issue in accessing any public member from just about anywhere else. These programmers have some difficulty making the transition to a header based language, such as C or C++, where they cannot easily do this. Of course, the need or desire to access these members in this fashion may or may not be a symptom of poor design, but that is an entirely different discussion.

.NET (C++ and Managed C++)

If you’re using .NET (I was using version 2003 or 1.1 for those of you at home), you can just add at the top of your form .h files the following line of code:

Code:

#pragma once

You can now safely #include all your forms in each other.

Not .NET (C, C++, Objective C, etc.)

If you are not using .NET, and are suffering from this problem, you can use some #defines to fix it.

In your first .H, include the following code at the top, changing ‘MYCLASSNAME’ as appropriate:

Code:

#ifndef MYCLASSNAME_H
#define MYCLASSNAME_H

and at the end of the .h file:

Code:

#endif //#ifndef MYCLASSNAME_H

This way, your header is only included one time, and only the first time it is used in any particular hierarchy. Remember that the ‘MYCLASSNAME’ symbol must be unique, if your class name happens to be a simple/common name, you may wish to prefix it with something unique (such as your name or initials).

Note: In Objective C, you can alternatively use the #import directive. — Curtis

Comments

Leave a Reply

You must be logged in to post a comment.