Sunday 16 September 2018

class vs struct

Class

  • class is reference type.
  • class object is created on Heap memory.
  • For class member variable can initialised directly.
  • class have constructor and destructor methods of all types.
  • class can inherit another class.
  • class are good for larger or complex object.

Struct


  • struct is value type.
  • struct object is created on Stack memory.
  • For struct member vaiable can not initialised directly.
  • struct can't be abstract.
  • stucts are good for small and isolated model object.  


Example of class

created one Student class with name and lname property with init method
class Student{
    var name : String?
    var lname : String?
    init(name : String?,lname : String?) {
        self.name = name
        self.lname = lname
    }

}
- now create one object for Student class called objStudent and print
let objStudent = Student(name: "Pratik", lname: "Lad")
dump(objStudent)

Output :
__lldb_expr_44.Student #0
  name: Optional("Pratik")
    - some: "Pratik"
  lname: Optional("Lad")
    - some: "Lad"

- now one more object create and assign older object of Student class
let obj1Student = objStudent
- now change the name of obj1Student object
obj1Student.name = "Bunty"
- now print both object 
dump(objStudent)

Output :
__lldb_expr_44.Student #0
  name: Optional("Bunty")
    - some: "Bunty"
  lname: Optional("Lad")
    - some: "Lad"

dump(obj1Student)

Output :
__lldb_expr_44.Student #0
   name: Optional("Bunty")
    - some: "Bunty"
   lname: Optional("Lad")
    - some: "Lad"
you can see the objStudent object name also change because class is reference type.

Example of struct

created one Student struct with name and lname property with init method
struct Student{
    var name : String?
    var lname : String?
    init(name : String?,lname : String?) {
        self.name = name
        self.lname = lname
    }

}
- now create one object for Student struct called objStudent and print
let objStudent = Student(name: "Pratik", lname: "Lad")
dump(objStudent)

Output :
__lldb_expr_44.Student #0
   name: Optional("Pratik")
    - some: "Pratik"
   lname: Optional("Lad")
    - some: "Lad"

- now one more object create and assign older object of Student struct
var obj1Student = objStudent
- now change the name of obj1Student object
obj1Student.name = "Bunty"
- now print both object 
dump(objStudent)

Output :
__lldb_expr_44.Student #0
   name: Optional("Pratik")
    - some: "Bunty"
   lname: Optional("Lad")
    - some: "Lad"

dump(obj1Student)

Output :
__lldb_expr_44.Student #0
   name: Optional("Bunty")
    - some: "Bunty"
   lname: Optional("Lad")
    - some: "Lad"
you can see the objStudent and obj1Student object name not change because struct is value type.

Thanks for reading this article.



No comments:

Post a Comment