简体   繁体   中英

Inherit C++ class from protobuf

I have objects of two types: TActionInfo and TActionStats. The first one describes action's characteristics and the second one can "eat" the first one and maintain some statistics based on many actions.

It is very convenient to use a protobuf in my task, because these objects are frequently serialized and deserialized.

It seems to be a good idea that TActionStats should have a method like

bool AddAction(const TActionInfo& action);

Is it a good idea to inherit a class from from google-protobuf TActionStats class? It is a good idea to inherit smth from protobuf in general?

No, you should not subclass protobuf types.

Consider what would happen if you embedded a TActionStats inside some other message type:

message TEnvelope {
  optional TActionStats stats = 0;
  optional string recipient = 1;
}

Now when you call stats() or mutable_stats() on a TEnvelope , you will receive a TActionStats , not your subclass. If you have a bunch of code that expects specifically to receive your subclass, you won't be able to call that code (without making a copy), so now you have to rewrite everything.

Instead, write your helper methods as independent, free-standing functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM