Why doesn't this compile:
[edit]sorry got slightly ahead of myself
Code:class b; class a { public: int m_a; a () { }; a (b *bb) { m_a = bb->m_b; }; }; class b { public: int m_b; b () { }; b (a *aa) { m_b = aa->m_a; }; };
Why doesn't this compile:
[edit]sorry got slightly ahead of myself
Code:class b; class a { public: int m_a; a () { }; a (b *bb) { m_a = bb->m_b; }; }; class b { public: int m_b; b () { }; b (a *aa) { m_b = aa->m_a; }; };
Last edited by drt; 03-29-2006 at 03:37 PM.
A forward reference doesn't let you declare an object of the class (or in your case a pointer to an object), it only allows you to refer to the class name. Why? Because nowhere in your forward reference does it say b contains a member m_b. The compile needs to know that.Code:a (b *bb) { m_a = bb->m_b; };
If you want to create an object of b, you have to define this function after you define the b class.
Last edited by SlyMaelstrom; 03-29-2006 at 03:52 PM.
Sent from my iPadŽ
Then how would you create a set of classes that are distinct but should be able to construct each other?
Example: a Euler angle and quaternion class.
Are you serious? Is that the best example you can give?Originally Posted by drt
Anyway, as I was saying, you can have classes construct each other, but you have to define all of the classes before you do any of the implementation. Using your example above:Code:#include <iostream> using namespace std; class b; class a { friend class b; // Why? Because the data memebers should be private public: a (int val = 0) : m_a(val) {}; a (const b&); // We'll define this outside of the class int getVal() { return m_a; } private: int m_a; }; class b { friend class a; public: b (int val = 0) : m_b(val) {}; b (const a&); int getVal() { return m_b; } private: int m_b; }; // Now we implement the overloaded constructors a::a (const b &bb) { m_a = bb.m_b; }; b::b (const a &aa) { m_b = aa.m_a; }; int main() { a aObj1(5); b bObj1(aObj1); a aObj2(bObj1); cout << bObj1.getVal() << endl << aObj1.getVal(); cin.get(); return 0; }
Sent from my iPadŽ
I tried to think of a better example, but imagination failed me.
This seems to work anyway, thanks.
I think you can declare a pointer to an object of a class that has only been forward declared, but can't use operator->() on it.