I am trying to get into C++ and I encountered few issues. My two classes look like that:
#include "Account.h"
class Program
{
public:
Program(void);
~Program(void);
void SetAccount(Account account);
};
#include "Program.h"
class Account
{
public:
Program *program;
Account(void);
~Account(void);
};
By passing an instance of the Account class to SetAccount function am I making a copy of it or I am passing it as a reference? As I understand I am making a copy of it, but I wanted to be sure. To pass it as a reference I need to use pointers, right?
Another issue I encountered is with my Account class. Lets say it needs to have Program class reference at some point. The problem is that both Program and Account classes have lines "#include" to each other so it causes circular dependency. Any ideas how to solve it?
Edited
My classes now looks like that:
#include "Account.h"
class Program
{
public:
Program();
~Program();
void SetAccount(Account account);
};
class Program;
class Account
{
public:
Program *program;
Account();
~Account();
};
When I try to initialize *program in Account constructor I get "incomplete type is not allowed" and "'Program' : no appropriate default constructor available".
In your definition of
void SetAccount(Account account);
the class Account must be known at compiletime, so you have to include the definition before it.
In your account class you are using only a pointer, so you can make a forward declaration
class Program;
class Account
{
public:
Program *program;
...
};
This is just to tell the compiler that a definition of an object named Program exists, but the size of the object is not necessarily known. As long as only a pointer is required, that is enough. If you want to dereference such a pointer you have to provide the class definition then.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With