Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I have a MFC application. in this application i want to access variable of one class into another class. Since MFC doesnot have a main function i am not able to perform friend class operation. in one class the variable values are assigned and another class i need to access this variable and use for some operation. is there any best way to do that in MFC? i dont want to use extern concept here.

What I have tried:

tried friend class concept and extern concept works but dont want to use extern concept
Posted
Updated 1-Apr-23 6:26am

You have two possibilities: use an instance, or use a static variable.

When you create a new instance of a class, you can access all the public variables the class contains as long as you have the pointer to that instance: it's like a car in that all cars have a glove box, but each car has a separate glove box. If you put your mobile in the glove box of your car it does not appear in the glove box of my car! To access the glove box content, you need to access the car first - you need a specific instance of the Car class in order to get at your phone.

Static variables are different: there is only one of them and it is shared by all instances of the class. This is similar to the "number of wheels" property of a car - all cars share the same number of wheels (four) because if they had two they would be a motorbike.

Start by looking at your code, and at your classes: if the data may be different between two instances of your class, you need to use the right instance to access it - if it's always the same for all instances, you could use static
 
Share this answer
 
In MFC you can use Document/View Architecture
https://learn.microsoft.com/en-us/cpp/mfc/document-view-architecture?view=msvc-170

Place your data in the document class and access it as follows:
C++
CMyDoc* pDoc = GetDocument();
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900