Can I define a library with classes like this? Please excuse any syntax errors, I am relearning my C/C++, been in C# for too long.
Here is my h file
class A;
class B
{
public:
B(A* a);
private:
A* _a;
};
class A
{
public:
A();
private:
B _b;
};
Here is my cpp file:
B::B(A* a)
{
_a = a;
}
A::A()
{
_b = B(this);
}
I want to be able to access A from B and B from A. After searching the web I found this but it does not seem to compile.
Can I do this? If I can what am I doing wrong. Here are the errors I am getting…
MyLib.cpp: In constructor 'A::A()':
MyLib.cpp:15: error: no matching function for call to 'B::B()'
MyLib.cpp:10: note: candidates are: B::B(A*)
MyLib.h:44: note: B::B(const B&)
Mutual dependency is usually not a good idea. Try to abstract out the dependency in one direction into an interface that the other class can implement. You need to design the two classes so that they do not need to be constructed simultaneously, which means that they need different life cycles. Perhaps if your example was more tangible, we could understand the relationship between the two classes better and suggest the best way to implement that relationship.
I use Ruby (actually JRuby) to program on my PC. Ruby is and always was entirely object oriented.
However ...
A donkey in a field knows more about object oriented programming than an AVR microcontroller (or a PIC for that matter).
It doesn't seem to make much sense worrying about OOP for an Arduino unless you can be sure the compiler is smart enough to magic it all away and produce simple efficient code in its place.
It's worth wasting CPU cycles and memory on a PC to make life easier for the programmer because the PC has so much power compared to a microcontroller.
You guys are probably right. I actualy did determine I did not need the circular refs. Thanks for the help though. I do have another question but I will create a new thread for it.
Not necessary, if you make the above modification.
When, exactly, is this defined? A's constructor is not complete when _b is initialized. Or, is it? How can it be when A depends on _b being valued.
Whereas A contains a B object, B only contains a pointer to an A. When B's constructor is called, it is passed (and stores) the pointer to the incomplete A. There might well be a problem if, in addition to storing the pointer to A, B's constructor called member functions of A using that pointer.