Reputation: 64366
I have an object of class which has private constructor:
class CL_GUIComponent
{
// ...
private:
CL_SharedPtr<CL_GUIComponent_Impl> impl;
CL_GUIComponent(CL_GUIComponent &other);
CL_GUIComponent &operator =(const CL_GUIComponent &other);
CL_GraphicContext dummy_gc;
};
I have a class which has a pointer to the object of the type I described before.
class Some
{
private:
CL_GUIComponent *obj;
public:
CL_GUIComponent getComp() { return *obj; }
}
But this code calls the error:
In member function ‘CL_GUIComponent Some::getComp()’:
error: ‘CL_GUIComponent::CL_GUIComponent(CL_GUIComponent&)’ is private
error: within this context
How can I store and get that object?
Upvotes: 1
Views: 1793
Reputation: 179
Since the constructor is declared private, you have to use a public member function to create an object of class that uses the private constructor.
class CL_GUIComponent
{
// ...
private:
CL_GUIComponent();
CL_GUIComponent(CL_GUIComponent &other);
CL_GUIComponent &operator =(const CL_GUIComponent &other);
public:
CL_GUIComponent* CreateInstance()
{
CL_GUIComponent *obj = new CL_GUIComponent();
}
};
class Some
{
private:
CL_GUIComponent *obj;
public:
CL_GUIComponent* getComp() { return (obj->CreateInstance()); }
};
Upvotes: 0
Reputation: 137930
Use getComp()
to initialize a reference.
CL_GUIComponent const &mycomp = getComp();
Then the language doesn't try to invoke the copy constructor inside the calling function. (getComp
does still create and return a copy, though.)
Upvotes: 0
Reputation: 84239
This is non-copyable idiom in action. Return by pointer or reference.
Upvotes: 0
Reputation: 23629
getComp returns an instance of CL_GUIComponent. This means that getComp will actually make a copy of the instance pointed to by obj. If you want getComp to return the instance where obj is pointing to, return a reference to CL_GUIComponent, like this:
CL_GUIComponent &getComp() {return *obj;}
Upvotes: 0
Reputation: 40897
By pointer or reference. You can't construct a new one and thus can't return copies, as your get attempts to do.
Upvotes: 2
Reputation: 54300
Return a reference instead:
CL_GUIComponent& getComp() { return *obj; }
and/or
const CL_GUIComponent& getComp() const { return *obj; }
The code you have their is trying to return a copy, but the copy constructor is private so it can't access it (hence the error). In any case, for non trivial objects, it's almost always better to return a const&
instead (in general, not always).
Upvotes: 5