简体   繁体   中英

Class in a struct

I have two questions.

  1. I know it is possible to declare class objects in structs. But is it ethical to do that from design point of view?

  2. In my scenario I have a structure with a huge number of member elements and I want to include a class object too. Here I have another question. If I memset() the whole struct the class handle is also reset. So, I check the size of the rest of the struct without the class object and subtract it while I call memset(), to get rid of this problem. (Please note that I am using STL class 'queue' here. And I cannot use sizeof() operator on the object, since it is not overloaded.)

But is this totally an unacceptable way to do that? Can you suggest some solution to this problem?

  • struct = class (except for default visibility).

  • If you have a “huge number of members” you are probably doing something wrong, change your design, otherwise it becomes intractable.

  • It is absolutely fine to nest classes and / or structs, where it makes sense. For instance, it's common to define nested classes for implementation details (so a linked_list class could have a node member class).

  • There's no such thing as a “class object”, and it's not clear what you mean by that.

  • Don't use memset – you probably don't need it, just use normal constructors and assignment.

  • And I cannot use sizeof() operator on the object

    Wrong, you can use it.

The solution is to avoid memset with classes and structures, and use constructors. In C++11 you can use initialization lists too under various conditions.

There is no much functional difference between classes and structs in c++. Structs exisist in c++ only for backward compatibility with C. So it is ok to have a class objects in structs. However I generally prefer structs that have only member variables with getter and setter. I dont use any functions inside struct that manupulate the data. If i need that then i will use class.

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