I have a class that is used to build another object. However, there are two methods of building this object that I can't decide between. Which method would potentially be the best? Opinions?
Example A
The first one consist of the outside class being a friend of the object its building and it just builds the object by accessing the its private data members.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
class Built
{
int data;
};
class Builder
{
friendclass Built;
Built* BuildObject()
{
object = new Built;
object.data = 0;
return object;
}
private:
Built* object;
};
Example B
The second one consists of the Built class, more or less building itself.
In the first example I think Built should declare Builder as a friend, not the way you have it. I also think that the first option is better. This may be one of the rare occasions where friend classes can enhance your encapsulation, assuming you want all the users of your class to invoke the Builder to get a Built object and not ever invoke a Built constructor directly.
EDIT: Something like this (haven't tested)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
class Builder; //forward declare
class Build
{
Build();
friendclass Builder;
int data;
};
class Builder
{
public:
static Build* BuildObject()
{
Build* object = new Build();
object->data = 0;
return object;
}
}