Search code examples
c++visual-studio-2010classmfcidentifier

C++ Can I use Identifiers in another class?


I am new to C++ so I'm not sure how to do this. Basically I have some identifiers of type CEdit declared in PvUiSampleDlg.h. They are used in PvUiSampleDlg.cpp.

CEdit mIPEdit;
CEdit mMACEdit;
CEdit mManufacturerEdit;
CEdit mModelEdit;
CEdit mNameEdit;

What I have done is created another class called SettingsDlg.cpp and I want to use the same identifiers in this class as well. How do I go about doing this? I am assuming that you have to get the identifiers in the SettingsDlg.h but I am not sure how to do that. I have #include PvUiSample.h in both the SettingsDlg.cpp and SettingsDlg.h. Any help would be appreciated.


Solution

  • It looks like you're looking for the extern keyword.

    When you declare your variables put extern infront of them. This lets the compiler/linker know that these variables will be used outside of this file.

    //PvUiSampleDlg.h
    extern CEdit mIPEdit;
    extern CEdit mMACEdit;
    extern CEdit mManufacturerEdit;
    extern CEdit mModelEdit;
    extern CEdit mNameEdit;
    

    Make sure you only initialize your variables in one place.

    //PvUiSampleDlg.cpp
    #include "PvUiSampleDlg.h"
    
    CEdit mIPEdit(/* your constructor args*/); // You can initialize like this
    ...
    void someFunc(){
        return mIpEdit;  // do something with your variable as you would normally
    }
    

    You can initialize the your variable as seen above. Make sure you include the header containing your extern variables otherwise the initialization will treat it like a normal static variable.

    Then in any other file including your header, you can use these variables as you would expect.