Eddy Haselhoff
Eddy Haselhoff

Reputation: 9

C++ return a class instance with private constructor

Hey I´ve got a Problem with a Class. It´s supposed to have a Method which returns the same class but with an other private constructor. But it fails with the specific error:

error C2248: 'std::basic_ios<_Elem,_Traits>::basic_ios' :
          cannot access private member declared in class '

This is the header file:

class XMLClass {
private:

    bool isGood();
    std::vector<std::string> xmlRowList;
    std::fstream xmlFS;
    XMLClass(std::string newList);

public:

    XMLClass(char *filename,std::string root);
    std::string getAttribute(char *att);
    std::string getText(void);
    XMLClass getChildNode(std::string childNode);
};

And this is the method which makes the error:

XMLClass XMLClass::getChildNode(std::string Node)
{
    XMLClass newXML(Node);
    return newXML;
}

Upvotes: 0

Views: 301

Answers (2)

jrok
jrok

Reputation: 55395

The problem is fstream class member - streams are non-copyable and as a consequence, so is your class.

To return an object from function by value, you need a copy constructor. But you don't have one because default generated one would be ill-formed.

If you've got C++11 support, you can implement move constructor for your class. If not, you'll need to store a pointer to the stream.

Upvotes: 4

hyde
hyde

Reputation: 62797

Someone will probably write a more detailed answer, but I Think problem is This:

std::fstream xmlFS;

You can't copy it, which is needed for this return by value:

return newXML;

Solution should be to write copy constructor and assignment operator for your class, which handle this member variable correctly.

Check out C++ Rule of Three while you are at it.

Upvotes: 1

Related Questions