Reputation: 1341
I was wondering what is the best practice re. passing (another class) amongst two instances of the same class (lets call this 'Primary'). So, essentially in the constructor for the first, i can initialize the outside instance (lets call this 'Shared') - and then set it to a particular value whilst im processing this class in main().
So 'Shared', may be an int, say 999 by now.
Now what if i create another instance of the main class 'Primary'? whats the best way to access the already initialized outside instance of 'Shared' - because if i don't handle this correctly, the constructor for 'Primary', when called again will just go ahead and create one more instance of 'Shared', and thus i loose the value 999.. i can think of some messy solutions involving dynamic pointers and if statements (just) but i have a feeling there might be a simpler, cleaner solution?
Upvotes: 0
Views: 667
Reputation: 5637
This depends on the semantics of your classes. If the outside class is not really outside but some obscure implementation detail that happens to be shared between instances, pass the first instance to the constructor of the second instance and get a reference to the outside instance there.
If the outside class is really an outside class with a meaning by itself, create it outside and pass it to the constructor just as Mark suggested.
If not only two specific instances but all instances share the same instance of the outside class, think about making it a static member of the class, as Martin York suggested.
Upvotes: 0
Reputation: 264669
As I understand it:
You did not mention if any parameters from the A constructor are used to initialize B!
What happens to the parameters of the second A that are used for B?
So we will assume that B is default constructed.
We will also assume that you need the instance of B to be lazily evaluated otherwise you would just use a static member.
class A
{
B& bRef;
public:
A()
:bRef(getLazyB()) // Get a reference to the only B for your object.
{}
private:
static B& getLazyB()
{
static B instance; // Created on first use
return instance; // returned to all users.
}
};
Upvotes: 3
Reputation: 32710
Make the constructor take a pointer or reference to the shared class. It is easier to construct outside.
class Shared;
class Same
{
shared& shared_;
Same( Shared& s ) { shared_ = s; }
}
With appropiate use of const and other constructors etc.
Upvotes: 2