views:

91

answers:

6

Hello, 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?

+5  A: 

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).

Peter Alexander
This doesn't solve his problem since he clearly can't modify that function.
Potatoswatter
+2  A: 

By pointer or reference. You can't construct a new one and thus can't return copies, as your get attempts to do.

Noah Roberts
I thought that I'm returning a reference, not the copy?
Ockonal
Donotalo
A: 

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;}
Patrick
A: 

This is non-copyable idiom in action. Return by pointer or reference.

Nikolai N Fetissov
A: 

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.)

Potatoswatter
A: 

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()); } };

Lakshmi