I'm trying to make a Builder (design pattern) for my class (C++). I have a function called BookBuilder::start() which is defined as static function and it returns a BookBuilder
BookBuilder BookBuilder::start()
{
mybook = new Book;
return *this;
}
But I'm unable to compile the code since a static member function can't access this
pointer. How may I return a BookBuilder if I don't have access to it? The final usage of the builder will look like this:
Author* markTwain = new Author("Mark Twain", "[email protected]", MALE);
Book* tomSawyer = BookBuilder::start()
.withTitle("The Adventures of Tom Sawyer")
.publishedBy("American Publishing Company")
.writtenBy(*markTwain)
.genre("Adventure")
.isbn(68934)
.hasPrice(100.99)
.allocate();
The private part of the class BookBuilder contains only one variable which is a pointer to Book.
Book* mybook;
Just return a newly constructed object:
BookBuilder BookBuilder::start()
{
return new BookBuilder();
}
But your function is quite strange. In builder pattern you construct the desired instance in build()
method. Earlier you just provide elements needed to construct the final object. See simple example:
class BookBuilder {
private String title;
private BookBuilder() {
}
public static BookBuilder start() {
return new BookBuilder();
}
public BookBuilder withTitle(final String title) {
this.title = title;
return this;
}
public Book allocate() {
return new Book(title);
}
}
This code is written in Java. It should be easy to convert it to C++.