devxlogo

Structs as a shorthand for public classes

Structs as a shorthand for public classes

Traditionally, structs serve as data aggregates. However, in C++ a struct can have constructor(s), destructor and member functions just like a class. The only difference between the two is the default access type: a class has by default private access type to its members and derived objects, whereas a struct has by default public access to its members and derived objects. Therefore, structs can be used as a shorthand for classes whose members are all public rather than being confined to the traditional role of ‘plain old data’ containers. A good example for that is the case of abstract classes:

 struct File { //all members are implicitly public	virtual int Read()  = 0; 	File(FILE *);	virtual ~File();};class TextFile: File {//implicit public inheritance; File is a struct	string path; //private member	//...other private members 	public:	int Flush();	int Read();};class UnicodeFile : TextFile { //implicit private inheritance	//...};

devx-admin

Share the Post: