skip to main |
skip to sidebar
- A struct is a value type, while a class is a reference type.
- When we instantiate a class, memory will be allocated on the heap. When struct gets initiated, it gets memory on the stack.
- Classes can have explicit parameter less constructors. But structs cannot have this.
- Classes support inheritance. But there is no inheritance for structs. A struct cannot inherit from another struct or class, and it cannot be the base of a class. Like classes, structures can implement interfaces.
- We can assign null variable to class. But we cannot assign null to a struct variable, since structs are value type.
- We can declare a destructor in class but can not in struct.
The struct type is good for representing lightweight objects such as Point, Rectangle, and Color. Although it is possible to represent a point as a class, but a struct is more efficient in some scenarios. i.e. if you declare an array of 3000 Point objects, we will allocate additional memory for referencing each object. In this case, the struct is less expensive.
ReplyDeleteStructures can be inherited the same way as classes.
ReplyDeleteDifference between structures and classes:
1)Structures have all parameters as public by default but classes have the members private by default.
2)Structures are allocated memory at stack and objects are allocated memory at heap.
But if the structure is allocated memory dynamically, then again the memory is allocated at heap
e.g struct SOAP s = new SOAP();
Can someone give an example of Structures implementing interfaces?
ReplyDeleteI thought structures are as good as user defined types.