Reputation: 295
In the below example I want to be able to access vector cList
in class B
in the function ShareData
. How do I do that?
I have written a sample code. It fails to compile (Error message: B has no constructors). Even if it did, does the line cObj = new B(*this);
introduce any circular dependency?
#include "stdafx.h"
#include <vector>
class B;
class A
{
public:
B* cObj;
std::vector<B*> cList;
A()
{
cObj = new B(*this);
}
};
class B
{
public:
B(A& aObj) : aObjLocal(aObj) {};
void ShareData(int result)
{
for (auto& iterator : aObjLocal.cList)
{
(*iterator).ShareData(result);
}
}
private:
A& aObjLocal;
};
void main()
{
A aMain;
B bMain(aMain);
bMain.ShareData(10);
}
Thanks in advance for sharing the knowledge.
Upvotes: 0
Views: 76
Reputation: 206717
The line
cObj = new B(*this);
does not work in A
's constructor since the definition of B
is not visible at that line. Move the implementation of A
's constructor after B
has been defined.
class A { ... };
class B { ... };
inline A::A()
{
cObj = new B(*this);
}
Upvotes: 1
Reputation: 11
cObj = new B(*this);
You cann use B here since it's not yet defined.
Put this under the definition of B:
A::A()
{
cObj = new B(*this);
}
and remove the inline definition.
Upvotes: 1
Reputation: 62613
When you are using forward declarations, you need to make sure that any usage of the forward-declared type which needs full type happens after the type becomes fully defined.
In your case, it means that your code should like following:
class B;
class A
{
public:
B* cObj;
std::vector<B*> cList;
A();
};
class B {
...
};
inline A::A()
{
cObj = new B(*this);
}
Also, while doing so, you certainly would want to get rid of owning B*
, and instead use std::unique_ptr
there.
Upvotes: 2