Can I create the c++ generate class instance with default value.

11 views
Skip to first unread message

童虎

unread,
Sep 8, 2020, 9:44:37 PM9/8/20
to Protocol Buffers
I have a protobuf like this:

```
syntax = "proto2";
message Foo {
required int foo1 = 1;
required int foo2 = 2;
...
required int foo20 = 20;
}
```

When I use the generated Foo class in c++. I want to create a instance serialized it. Looks like this:

```
Foo foo;
foo.set_foo1(1);
// What I want is ommit the others with them default value.
string fb;
foo.SerializeToString(&pb);
```
But at runtime, this will throw exception says "The foo2...foo20" is not setted.

What I want is default value 0. Setting them seems like boring 

Can I do this. My english is poor, If you can't understand me, please let me know. Thank you.

Adam Cozzette

unread,
Sep 9, 2020, 11:30:20 AM9/9/20
to 童虎, Protocol Buffers
With some effort you can do this using the reflection API, but if possible it would be even better to avoid using required fields.

--
You received this message because you are subscribed to the Google Groups "Protocol Buffers" group.
To unsubscribe from this group and stop receiving emails from it, send an email to protobuf+u...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/protobuf/629f1220-8523-4d2d-a3a4-41d296113d01n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages