bidirectional association between 2 classes

c++, visual-c++, visual-studio-2012

Solution

You have a circular include dependency, but in this case, since class A only holds a container of pointers of class B, and vice versa, you can use forward declarations, and put the includes in the implementation files.

So, instead of

 #include "account.h"

use

class Account;

Unrelated: do not put `using namespace std` in header files, and if possible, nowhere. See here for more on that issue.

Problem

Im wanted to create a bidirectional association between 2 classes. For example `class A` has `class B` as its private attribute and `class B` has `class A` as its private attributes. Errors which I have gotten is mainly: ``` Error 323 error C2653: 'Account' : is not a class or namespace name Error 324 error C2143: syntax error : missing ';' before '{' ``` (i get loads of such error) I believe these errors got to do with how i include paymentMode.h in account.h and vice versa. I tried commenting off one inclusion in one of the classes and things work fine. May I ask how to remove such errors while I can still have my bidirectional association between account and paymentMode class? Thank you! Attached are the codes that I have written. ``` //paymentMode.h #pragma once #ifndef _PAYMENTMODE_H #define _PAYMENTMODE_H #include <string> #include <iostream> #include <vector> #include "item.h" #include "account.h" using namespace std; class PaymentMode { private: string paymentModeName; double paymentModeThreshold; double paymentModeBalance; //how much has the user spent using this paymentMode; vector<Account*> payModeAcctList; public: PaymentMode(string); void pushItem(Item*); void addAcct(Account*); string getPaymentModeName(); void setPaymentModeName(string); void setPaymentModeThreshold(double); double getPaymentModeThreshold(); void setPaymentModeBal(double); double getPaymentModeBal(); void updatePayModeBal(double); int findAccount(string); void deleteAccount(string); }; #endif //account.h #pragma once #ifndef _ACCOUNT_H #define _ACCOUNT_H #include <string> #include <iostream> #include <vector> #include "paymentMode.h" using namespace std; class Account { private: string accountName; //vector<PaymentMode*> acctPayModeList; double accountThreshold; double accountBalance; //how much has the user spent using this account. public: Account(string); //void addPayMode(PaymentMode*); //int findPayMode(PaymentMode*); string getAccountName(); void setAccountName(string); void setAccountThreshold(double); double getAccountThreshold(); void setAccountBal(double); double getAccountBal(); void updateAcctBal(double); }; #endif ```

Original source

Related problems