Docsity

Object-Oriented Programming: Destructors and Constructor Overloading, Lecture notes of Object Oriented Programming

Partial preview of the text

Download Object-Oriented Programming: Destructors and Constructor Overloading and more Lecture notes Object Oriented Programming in PDF only on Docsity!

Destructor

  • (^) Naming Convention : A destructor has the same name as the class but is preceded by a tilde (~).
  • (^) Syntax : ~ClassName()
  • (^) No Parameters and Return Type: Destructors cannot take parameters. They do not return any value, not even void.
  • (^) Automatic called : Destructors are called automatically when an object is destroyed. They cannot be called explicitly like regular member functions.
  • (^) One Destructor per Class: A class can have only one destructor. If not explicitly defined, the compiler provides a default destructor.
  • (^) The most common use of destructors is to deallocate memory that was allocated for the object by the constructor.
  • Lecture
  • Example
  • Example

Example 3

  • (^) Since there are now two explicit constructors with the same name, Distance(), we say the constructor is overloaded. - (^) Which of the two constructors is executed when an object is created depends on how many arguments are used in the definition:

Example 3 Member function defined outside the class

  • (^) Which of the two constructors is executed when an object is created depends on how many arguments are used in the definition:

It is only declared inside the cla

This tells the compiler that this function is a member of the class but that it will be defined outside the class declaration, someplace else in the listing.

  • (^) The function name, add_dist(), is preceded by the class name, Distance, and a new

symbol—the double colon (::).

  • (^) This symbol is called the scope resolution operator.
  • (^) It is a way of specifying what class something is associated with.
  • (^) In this situation, Distance::add_dist() means “the add_dist() member function of the

Distance class.”

Objects as an arguments

Default copy constructor

  • (^) You don’t need to create a special constructor for this; one is already built into all classes. It’s called the default copy constructor

Returning objects from function