Skip to content

Instantly share code, notes, and snippets.

@jaredsburrows
Last active October 30, 2016 20:15
Show Gist options
  • Save jaredsburrows/3065ed97b67c8362293911809804398f to your computer and use it in GitHub Desktop.
Save jaredsburrows/3065ed97b67c8362293911809804398f to your computer and use it in GitHub Desktop.
C++ Builder Examples
// A.h
class A {
public:
int var;
class Builder;
A(Builder* builder);
int getVar();
Builder* newBuilder();
};
// Builder.h
class A::Builder {
public:
int var;
Builder();
Builder(A* a);
Builder withVar(int var);
A* build();
};
// A.cpp
A::A(Builder* builder) {
var = builder->var;
}
int A::getVar() {
return var;
}
A::Builder* A::newBuilder() {
return new Builder(this);
}
// Builder.cpp
A::Builder::Builder() {
var = 0;
}
A::Builder::Builder(A* a) {
var = a->var;
}
A::Builder A::Builder::withVar(int var) {
this->var = var;
return *this;
}
A* A::Builder::build() {
return new A(this);
}
// Example usage
int main(void) {
auto *a = A::Builder()
.withVar(123)
.build();
return 0;
}
class A {
private:
int var;
public:
class Builder;
A(Builder* builder) {
var = builder->var;
}
int getVar() {
return var;
}
Builder* newBuilder() {
return new Builder(this);
}
class Builder {
public:
int var;
Builder() {
var = 0;
}
Builder(A* a) {
var = a->var;
}
Builder withVar(int var) {
this->var = var;
return *this;
}
A* build() {
return new A(this);
}
};
};
// Example usage
// g++ test.cpp -std=c++11 -o test.o && ./test.o
int main(void) {
auto *a = A::Builder()
.withVar(123)
.build();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment