Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

automatic association in C++

Status
Not open for further replies.

raydona

Programmer
May 12, 2005
27
GB
In the following example adding a secretary to an office automatically adds that office to the secretary. How can I get the reverse association to be automatic, that is, adding an office to a secretary automatically adds that secretary to the office. Thanking you for your help.

//Secretary.h
#include <iostream>
using namespace std;
#include <string>
#include "Office.h"

class Office;
class Secretary
{ private:
char role[80];
Office* office;
public:
Secretary(char* role_in) { strcpy(role, role_in); }
char* getRole() { return role; }
void addOffice(Office* room) { office = room; }
Office* getOffice() { return office; }
};
#include "Secretary.h"

class Secretary;
class Office
{ private:
int room_number;
Secretary* secretary;
public:
Office(int number) { room_number = number; }
int getRoomNumber() { return room_number; }
Secretary* getSecretary() { return secretary; }
void addSecretary(Secretary* sec)
{ secretary = sec;
secretary->addOffice(this);
}
};
#include "Office.h"

void main()
{ Office* faculty_office = new Office(101);
Secretary* secretary = new Secretary("faculty secretary");
faculty_office -> addSecretary(secretary);
cout << "The " << secretary -> getRole() << " is in room ";
cout << secretary -> getOffice() -> getRoomNumber() << endl;
cout << "Room number " << faculty_office -> getRoomNumber() << " houses the ";
cout << faculty_office -> getSecretary() -> getRole() << endl;
}
 
Something like this:
Code:
class Secretary
{
private:
    char role[80];
    Office* office;
public:
    Secretary(char* role_in) { strcpy(role, role_in); }
    char* getRole() { return role; }
    void addOffice(Office* room)
    {
        office = room;
        office->secretary = this;
    }
    Office* getOffice() { return office; }
};

class Office
{
    friend class Secretary;
private:
    int room_number;
    Secretary* secretary;
public:
     Office(int number) { room_number = number; }
     int getRoomNumber() { return room_number; }
     Secretary* getSecretary() { return secretary; }
     void addSecretary(Secretary* sec)
     {
        secretary = sec;
        secretary->addOffice(this);
     }
};
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top