tailieunhanh - C++ Programming for Games Module I phần 7

Tham khảo tài liệu 'c++ programming for games module i phần 7', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả | leak. Note that you never invoke a destructor yourself rather the destructor will automatically be called when an object is being deleted from memory. Constructors and destructors are special methods and they require a specific syntax. In particular a constructor has no return type and its name is also the name of the class. Likewise a destructor has no return type no parameters and its name is the name of the class but prefixed with the tilde . This next snippet shows how the constructor and destructor would be declared in the Wizard class definition class Wizard public Constructor. Wizard Overloaded constructor. Wizard std string name int hp int mp int armor Destructor Wizard The implementations of these function is done just as any other method except there is no return type. The following snippet gives a sample implementation Wizard Wizard Client called constructor with zero parameters so construct a wizard with default values. We call this a default constructor. mName DefaultName mHitPoints 0 mMagicPoints 0 mArmor 0 Wizard Wizard std string name int hp int mp int armor Client called constructor with parameters so construct a wizard with the specified values. mName name mHitPoints hp mMagicPoints mp mArmor armor Wizard Wizard No dynamic memory to delete--nothing to cleanup. Note Observe that we have overloaded the constructor function. Recall that the act of defining several different versions which differ in signature of a function is called function overloading. We can overload methods in the same way we overload functions. 156 Constructors are called when an object is created. Thus instead of writing Wizard wiz0 We now write Wizard wiz0 Use default constructor. or Wizard wiz0 Gandalf 20 100 5 Use constructor with parameters. Note that the following are actually equivalent that is they both use the default constructor Wizard wiz0 Use default constructor. Wizard wiz0 Use default constructor. Copy Constructors and the Assignment Operator Every class also