Constructors and Destructors
Constructors
• A constructor is a special member function whose task is to initialize the objects of its class.
• It is special because its name is same as the class name.
• The constructor is invoked whenever an object of its associated class is created.
• It is called constructor because it constructs the values of data members of the class.
Constructor - example
class add
{
int m, n ;
public :
add (void) ;
------
};
add :: add (void)
{
m = 0; n = 0;
}
• When a class contains a constructor, it is guaranteed that an object created by the class will be initialized automatically.
• add a ;
• Not only creates the object a of type add but also initializes its data members m and n to zero.
Constructors
• There is no need to write any statement to invoke the constructor function.
• If a ‘normal’ member function is defined for zero initialization, we would need to invoke this function for
each of the objects separately.
• A constructor that accepts no parameters is called the default constructor.
• The default constructor for class A is A : : A ( )
continue …
Characteristics of Constructors
• They should be declared in the public section.
• They are invoked automatically when the objects are created.
• They do not have return types, not even void and they cannot return values.
Characteristics of Constructors
• They cannot be inherited, though a derived class can call the base class constructor.
• Like other C++ functions, Constructors can have default arguments.
• Constructors can not be virtual.
continue …
Characteristics of Constructors
• We can not refer to their addresses.
• An object with a constructor (or destructor) can not be used as a member of a union.
They make ‘implicit calls’ to the operators new and delete when memory allocation is required.
continue …
Constructors
• When a constructor is declared for a class initialization of the class objects becomes mandatory.
continue …
Parameterized Constructors
• It may be necessary to initialize the various data elements of different objects with different values when
they are created.
• This is achieved by passing arguments to the constructor function when the objects are created.
• The constructors that can take arguments are called parameterized constructors.
Parameterized Constructors
class add
{
int m, n ;
public :
add (int, int) ;
------
};
add : : add (int x, int y)
{
m = x; n = y;
}
• When a constructor is parameterized, we must pass the initial values as arguments to the constructor function when an object is declared.
• Two ways Calling:
• Explicit
• add sum = add(2,3);
• Implicit
• add sum(2,3)
• Shorthand method
Multiple Constructors in a Class
• C + + permits to use more than one constructors in a single class.
• Add( ) ; // No arguments
• Add (int, int) ; // Two arguments
Multiple Constructors in a Class
class add
{
int m, n ;
public :
add ( ) {m = 0 ; n = 0 ;}
add (int a, int b)
{m = a ; n = b ;}
add (add & i)
{m = i.m ; n = i.n ;}
};
• The first constructor receives no arguments.
• The second constructor receives two integer arguments.
• The third constructor receives one add object as an argument.
continue …
Multiple Constructors in a Class
class add
{
int m, n ;
public :
add ( ) {m = 0 ; n = 0 ;}
add (int a, int b)
{m = a ; n = b ;}
add (add & i)
{m = i.m ; n = i.n ;}
};
• Add a1;
• Would automatically invoke the first constructor and set both m and n of a1 to zero.
• Add a2(10,20);
• Would call the second constructor which will initialize the data members m and n of a2 to 10 and 20 respectively.
continue …
Multiple Constructors in a Class
class add
{
int m, n ;
public :
add ( ) {m = 0 ; n = 0 ;}
add (int a, int b)
{m = a ; n = b ;}
add (add & i)
{m = i.m ; n = i.n ;}
};
• Add a3(a2);
• Would invoke the third constructor which copies the values of a2 into a3.
• This type of constructor is called the “copy constructor”.
• Construction Overloading
• More than one constructor function is defined in a class.
continue …
Multiple Constructors in a Class
class complex
{
float x, y ;
public :
complex ( ) { }
complex (float a)
{ x = y = a ; }
complex (float r, float i)
{ x = r ; y = i }
------
};
• complex ( ) { }
• This contains the empty body and does not do anything.
• This is used to create objects without any initial values.
continue …
Multiple Constructors in a Class
C + + compiler has an implicit constructor which creates objects, even though it was not defined in the class.
• This works well as long as we do not use any other constructor in the class.
• However, once we define a constructor, we must also define the “do-nothing” implicit constructor.
continue …
Constructors with Default Arguments
• It is possible to define constructors with default arguments.
• Consider complex (float real, float imag = 0);
• The default value of the argument imag is zero.
• complex C1 (5.0) assigns the value 5.0 to the real variable and 0.0 to imag.
• complex C2(2.0,3.0) assigns the value 2.0 to real and 3.0 to imag.
Constructors with Default Arguments
• A : : A ( ) Default constructor

• A : : A (int = 0) Default argument constructor

• The default argument constructor can be called with either one argument or no arguments.
• When called with no arguments, it becomes a default constructor.
continue …
Dynamic Initialization of Objects
formats, using overloaded constructors.
This provides the flexibility of using
different format of data at run time
depending upon the situation.
• Providing initial value to objects at run time.
• Advantage – We can provide various initialization
Copy Constructor
integer (integer & i) ;
integer I 2 ( I 1 ) ; or integer I 2 = I 1 ;
The process of initializing through a copy constructor is
known as copy initialization.
• A copy constructor is used to declare and initialize an object from another object.
Copy Constructor
The statement
I 2 = I 1;
will not invoke the copy constructor.
If I 1 and I 2 are objects, this statement is legal and
assigns the values of I 1 to I 2, member-by-member.
continue …
Copy Constructor
• A reference variable has been used as an argument to the copy constructor.
• We cannot pass the argument by value to a copy constructor.
continue …
Dynamic Constructors
• The constructors can also be used to allocate memory while creating objects.
• This will enable the system to allocate the right amount of memory for each object when the objects are
not of the same size.
Dynamic Constructors
• Allocation of memory to objects at the time of their construction is known as dynamic construction of objects.
• The memory is created with the help of the new operator.
continue …
What is Garbage Collection?
Memory Management technique.
Process of freeing objects.
No longer referenced by the program.
Why Garbage Collection?
Free unreferenced objects.
Combat heap fragmentation.
Relieves programmer from manual freeing the memory.
Helps in ensuring program integrity.
Disadvantages
Extra Overhead.
Less control over scheduling of CPU time.
Destructors
eg: ~ integer ( ) { }
• A destructor is used to destroy the objects that have been created by a constructor.
• Like constructor, the destructor is a member function whose name is the same as the class name but is
preceded by a tilde.
Destructors
• A destructor never takes any argument nor does it return any value.
• It will be invoked implicitly by the compiler upon exit from the program – or block or function as the case
may be – to clean up storage that is no longer accessible.
continue …
Destructors
• It is a good practice to declare destructors in a program since it releases memory space for further use.
Whenever new is used to allocate memory in the constructor, we should use delete to free that memory.
continue …
Destructor Example
class Silly { private: string name; public: Silly(){ cout <<"A silly object is born!"<< endl; } ~Silly(){ cout <<"Silly
object "<<name<<" dies!"<< endl; } };
int main() { Silly *p; if (1>0){ Silly first; first.name = “Tom"; p = new Silly[2]; p[0].name = "John"; p[1].name = “Sara"; }
Silly last; last.name = “Tom Jr"; delete [] p;
return 0; }
Use?
When is destructor useful?
Executed when object destroyed
Can do anything, but interesting when deallocate
memory
Want to delete items created using new to free up
memory
Destructor Example
List::~List() {
while(head != 0) {
Node *p = head;
head = head->next;
delete p;
}
}
/** DEFINITION OF CLASS NODE **/
class Node {
public:
int data;
Node *next;
Node(int val, Node* p) {
data = val;
next = p;
}
};
Finalization
Finalization
• Finalize is very different from destructors.
• Finalizable objects get promoted to older generations, which increases memory pressure.
• All objects referred to directly or indirectly by this object get promoted as well.
• Forcing the garbage collector to execute a Finalize method can significantly hurt performance.
• Finalizable objects may refer to other (non-finalizable) objects, prolonging their lifetime unnecessarily.
Finalization
Finalization
• You have no control over when the Finalize method will execute. The object may hold on to resources until
the next time the garbage collector runs.
• If you determine that your type must implement a Finalize method, then make sure the code executes as
quickly as possible. Avoid all actions that would block the Finalize method
Finalization Internals
Finalization Internals
• Each entry in the queue points to an object that should have its Finalize method called before the object's
memory can be reclaimed.
Finalization Internals
Finalization Internals
• At this point, the garbage collector has finished identifying garbage.
• There is a special runtime thread dedicated to calling Finalize methods.
Finalization Internals
Finalization Internals
• The next time the garbage collector is invoked, it sees that the finalized objects are truly garbage.
• This time the memory for the object is simply reclaimed.
Resurrection
Resurrection
public class BaseObj {
protected override void Finalize() {
Application.ObjHolder = this;
GC.ReRegisterForFinalize(this);
}
}
• An object requiring finalization dies, lives, and then dies again, this phenomenon is called resurrection.
Thank You

constructocvbcvbcvbcvbr-Destructor (1).pptx

  • 1.
  • 2.
    Constructors • A constructoris a special member function whose task is to initialize the objects of its class. • It is special because its name is same as the class name. • The constructor is invoked whenever an object of its associated class is created. • It is called constructor because it constructs the values of data members of the class.
  • 3.
    Constructor - example classadd { int m, n ; public : add (void) ; ------ }; add :: add (void) { m = 0; n = 0; } • When a class contains a constructor, it is guaranteed that an object created by the class will be initialized automatically. • add a ; • Not only creates the object a of type add but also initializes its data members m and n to zero.
  • 4.
    Constructors • There isno need to write any statement to invoke the constructor function. • If a ‘normal’ member function is defined for zero initialization, we would need to invoke this function for each of the objects separately. • A constructor that accepts no parameters is called the default constructor. • The default constructor for class A is A : : A ( ) continue …
  • 5.
    Characteristics of Constructors •They should be declared in the public section. • They are invoked automatically when the objects are created. • They do not have return types, not even void and they cannot return values.
  • 6.
    Characteristics of Constructors •They cannot be inherited, though a derived class can call the base class constructor. • Like other C++ functions, Constructors can have default arguments. • Constructors can not be virtual. continue …
  • 7.
    Characteristics of Constructors •We can not refer to their addresses. • An object with a constructor (or destructor) can not be used as a member of a union. They make ‘implicit calls’ to the operators new and delete when memory allocation is required. continue …
  • 8.
    Constructors • When aconstructor is declared for a class initialization of the class objects becomes mandatory. continue …
  • 9.
    Parameterized Constructors • Itmay be necessary to initialize the various data elements of different objects with different values when they are created. • This is achieved by passing arguments to the constructor function when the objects are created. • The constructors that can take arguments are called parameterized constructors.
  • 10.
    Parameterized Constructors class add { intm, n ; public : add (int, int) ; ------ }; add : : add (int x, int y) { m = x; n = y; } • When a constructor is parameterized, we must pass the initial values as arguments to the constructor function when an object is declared. • Two ways Calling: • Explicit • add sum = add(2,3); • Implicit • add sum(2,3) • Shorthand method
  • 11.
    Multiple Constructors ina Class • C + + permits to use more than one constructors in a single class. • Add( ) ; // No arguments • Add (int, int) ; // Two arguments
  • 12.
    Multiple Constructors ina Class class add { int m, n ; public : add ( ) {m = 0 ; n = 0 ;} add (int a, int b) {m = a ; n = b ;} add (add & i) {m = i.m ; n = i.n ;} }; • The first constructor receives no arguments. • The second constructor receives two integer arguments. • The third constructor receives one add object as an argument. continue …
  • 13.
    Multiple Constructors ina Class class add { int m, n ; public : add ( ) {m = 0 ; n = 0 ;} add (int a, int b) {m = a ; n = b ;} add (add & i) {m = i.m ; n = i.n ;} }; • Add a1; • Would automatically invoke the first constructor and set both m and n of a1 to zero. • Add a2(10,20); • Would call the second constructor which will initialize the data members m and n of a2 to 10 and 20 respectively. continue …
  • 14.
    Multiple Constructors ina Class class add { int m, n ; public : add ( ) {m = 0 ; n = 0 ;} add (int a, int b) {m = a ; n = b ;} add (add & i) {m = i.m ; n = i.n ;} }; • Add a3(a2); • Would invoke the third constructor which copies the values of a2 into a3. • This type of constructor is called the “copy constructor”. • Construction Overloading • More than one constructor function is defined in a class. continue …
  • 15.
    Multiple Constructors ina Class class complex { float x, y ; public : complex ( ) { } complex (float a) { x = y = a ; } complex (float r, float i) { x = r ; y = i } ------ }; • complex ( ) { } • This contains the empty body and does not do anything. • This is used to create objects without any initial values. continue …
  • 16.
    Multiple Constructors ina Class C + + compiler has an implicit constructor which creates objects, even though it was not defined in the class. • This works well as long as we do not use any other constructor in the class. • However, once we define a constructor, we must also define the “do-nothing” implicit constructor. continue …
  • 17.
    Constructors with DefaultArguments • It is possible to define constructors with default arguments. • Consider complex (float real, float imag = 0); • The default value of the argument imag is zero. • complex C1 (5.0) assigns the value 5.0 to the real variable and 0.0 to imag. • complex C2(2.0,3.0) assigns the value 2.0 to real and 3.0 to imag.
  • 18.
    Constructors with DefaultArguments • A : : A ( ) Default constructor  • A : : A (int = 0) Default argument constructor  • The default argument constructor can be called with either one argument or no arguments. • When called with no arguments, it becomes a default constructor. continue …
  • 19.
    Dynamic Initialization ofObjects formats, using overloaded constructors. This provides the flexibility of using different format of data at run time depending upon the situation. • Providing initial value to objects at run time. • Advantage – We can provide various initialization
  • 20.
    Copy Constructor integer (integer& i) ; integer I 2 ( I 1 ) ; or integer I 2 = I 1 ; The process of initializing through a copy constructor is known as copy initialization. • A copy constructor is used to declare and initialize an object from another object.
  • 21.
    Copy Constructor The statement I2 = I 1; will not invoke the copy constructor. If I 1 and I 2 are objects, this statement is legal and assigns the values of I 1 to I 2, member-by-member. continue …
  • 22.
    Copy Constructor • Areference variable has been used as an argument to the copy constructor. • We cannot pass the argument by value to a copy constructor. continue …
  • 23.
    Dynamic Constructors • Theconstructors can also be used to allocate memory while creating objects. • This will enable the system to allocate the right amount of memory for each object when the objects are not of the same size.
  • 24.
    Dynamic Constructors • Allocationof memory to objects at the time of their construction is known as dynamic construction of objects. • The memory is created with the help of the new operator. continue …
  • 25.
    What is GarbageCollection? Memory Management technique. Process of freeing objects. No longer referenced by the program.
  • 26.
    Why Garbage Collection? Freeunreferenced objects. Combat heap fragmentation. Relieves programmer from manual freeing the memory. Helps in ensuring program integrity. Disadvantages Extra Overhead. Less control over scheduling of CPU time.
  • 27.
    Destructors eg: ~ integer( ) { } • A destructor is used to destroy the objects that have been created by a constructor. • Like constructor, the destructor is a member function whose name is the same as the class name but is preceded by a tilde.
  • 28.
    Destructors • A destructornever takes any argument nor does it return any value. • It will be invoked implicitly by the compiler upon exit from the program – or block or function as the case may be – to clean up storage that is no longer accessible. continue …
  • 29.
    Destructors • It isa good practice to declare destructors in a program since it releases memory space for further use. Whenever new is used to allocate memory in the constructor, we should use delete to free that memory. continue …
  • 30.
    Destructor Example class Silly{ private: string name; public: Silly(){ cout <<"A silly object is born!"<< endl; } ~Silly(){ cout <<"Silly object "<<name<<" dies!"<< endl; } }; int main() { Silly *p; if (1>0){ Silly first; first.name = “Tom"; p = new Silly[2]; p[0].name = "John"; p[1].name = “Sara"; } Silly last; last.name = “Tom Jr"; delete [] p; return 0; }
  • 31.
    Use? When is destructoruseful? Executed when object destroyed Can do anything, but interesting when deallocate memory Want to delete items created using new to free up memory
  • 32.
    Destructor Example List::~List() { while(head!= 0) { Node *p = head; head = head->next; delete p; } } /** DEFINITION OF CLASS NODE **/ class Node { public: int data; Node *next; Node(int val, Node* p) { data = val; next = p; } };
  • 33.
    Finalization Finalization • Finalize isvery different from destructors. • Finalizable objects get promoted to older generations, which increases memory pressure. • All objects referred to directly or indirectly by this object get promoted as well. • Forcing the garbage collector to execute a Finalize method can significantly hurt performance. • Finalizable objects may refer to other (non-finalizable) objects, prolonging their lifetime unnecessarily.
  • 34.
    Finalization Finalization • You haveno control over when the Finalize method will execute. The object may hold on to resources until the next time the garbage collector runs. • If you determine that your type must implement a Finalize method, then make sure the code executes as quickly as possible. Avoid all actions that would block the Finalize method
  • 35.
    Finalization Internals Finalization Internals •Each entry in the queue points to an object that should have its Finalize method called before the object's memory can be reclaimed.
  • 36.
    Finalization Internals Finalization Internals •At this point, the garbage collector has finished identifying garbage. • There is a special runtime thread dedicated to calling Finalize methods.
  • 37.
    Finalization Internals Finalization Internals •The next time the garbage collector is invoked, it sees that the finalized objects are truly garbage. • This time the memory for the object is simply reclaimed.
  • 38.
    Resurrection Resurrection public class BaseObj{ protected override void Finalize() { Application.ObjHolder = this; GC.ReRegisterForFinalize(this); } } • An object requiring finalization dies, lives, and then dies again, this phenomenon is called resurrection.
  • 39.