R2Delta
R2Delta

Reputation: 29

Access function variables between friend classes

Just wondering...how can I access the variable 'path' of ClassA function Open() from within another fucntion of class ClassB if both classes are declared 'friends'? I'm basically trying to populate a child window with info from the parent window when the child window is selected, although both windows have different classes.

ClassA.cpp:

void ClassA::Open() 
{ 
// Open Program Properties window 

ClassB dlg; 

dlg.DoModal(); 

CString path; 

path = m_DirTree.GetCurrentDir(); //Path specified by tree selection

}

ClassB.cpp:

void ClassB::Display(){

//HOW CAN I ACCESS 'path' HERE? 

SetDlgItemText(IDC_PATH, path); //Populate the edit box 

}

Thankyou for the replies...

Upvotes: 0

Views: 64

Answers (2)

Blacktempel
Blacktempel

Reputation: 3995

With your current code you can't.

After the function void ClassA::Open() your CString path; will be destroyed.

You could save your CString path; as member variable.

Or you could add a variable of CString to your function void ClassB::Display(), which could result in this code:

void ClassA::Open(void) 
{ 
    // Open Program Properties window 
    ClassB dlg; 
    dlg.DoModal(); 

    CString path; 
    path = m_DirTree.GetCurrentDir(); //Path specified by tree selection
    m_classBMember.Display(path);
}


void ClassB::Display(CString &path)
{
    SetDlgItemText(IDC_PATH, path); //Populate the edit box
}

Upvotes: 1

David Haim
David Haim

Reputation: 26546

You pass an A object by reference (or any other way to make the object visible to B::Display) and just excess it with '.' operator

void ClassB::Display(A &a){
    SetDlgItemText(IDC_PATH, a.path);
}

although you might want to consider exposing public set and get functions for these kind of variables

Upvotes: 1

Related Questions