Professional Documents
Culture Documents
Intructors: Abir
Das and
Sourangshu
Bhattacharya
Module 13: Programming in C++
Objectives & Constructors, Destructors & Object Lifetime
Outline
Constructor
Contrasting with
Member Functions
Parameterized Intructors: Abir Das and Sourangshu Bhattacharya
Default Parameters
Overloaded
Object Lifetime
Automatic Slides taken from NPTEL course on Programming in Modern C++
Static
Dynamic by Prof. Partha Pratim Das
Module Summary
Module 13
Constructor
Contrasting with
Member Functions
Parameterized
Default Parameters
Overloaded
Destructor
Contrasting with
Member Functions
Default
Constructor
Object Lifetime
Automatic
Static
Dynamic
Module Summary
Module 13
Intructors: Abir
1 Constructor
Das and
Sourangshu Contrasting with Member Functions
Bhattacharya
Parameterized
Objectives & Default Parameters
Outline
Overloaded
Constructor
Contrasting with
Member Functions 2 Destructor
Parameterized
Default Parameters
Contrasting with Member Functions
Overloaded
Destructor
3 Default Constructor
Contrasting with
Member Functions
4 Object Lifetime
Default
Constructor Automatic
Object Lifetime Static
Automatic
Static
Dynamic
Dynamic
Module Summary
5 Module Summary
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 3
Program 13.01/02: Stack: Initialization
Intructors: Abir • Is a static member function without this pointer – but gets • Has implicit this pointer
Das and
Sourangshu
the pointer to the memory where the object is constructed
Bhattacharya • Name is same as the name of the class • Any name different from name of class
class Stack { public: Stack(); }; class Stack { public: int empty(); };
Objectives &
Outline • Has no return type - not even void • Must have a return type - may be void
Constructor Stack::Stack(); // Not even void int Stack::empty();
Contrasting with • Does not return anything. Has no return statement • Must have at least one return statement
Member Functions
Parameterized
Stack::Stack(): top_(-1) int Stack::empty() { return (top_ == -1); }
Default Parameters { } // Returns implicitly void pop()
Overloaded { --top_; } // Implicit return for void
Destructor • Initializer list to initialize the data members • Not applicable
Contrasting with Stack::Stack(): // Initializer list
Member Functions
data_(new char[10]), // Init data_
Default top_(-1) // Init top_
Constructor
{ }
Object Lifetime
• Implicit call by instantiation / operator new • Explicit call by the object
Automatic
Static
Stack s; // Calls Stack::Stack() s.empty(); // Calls Stack::empty(&s)
Dynamic • May be public or private • May be public or private
Module Summary • May have any number of parameters • May have any number of parameters
• Can be overloaded • Can be overloaded
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 7
Program 13.06: Complex: Parameterized Constructor
Default c1.print();
Constructor c2.print();
Object Lifetime
c3.print();
Automatic
}
Static -----
Dynamic |4.2+j5.3| = 6.7624
|4.2+j0| = 4.2
Module Summary
|0+j0| = 0
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 9
Program 13.08: Stack: Constructor with default parameters
Default c1.print();
Constructor
c2.print();
Object Lifetime c3.print();
Automatic }
Static -----
Dynamic |4.2+j5.3| = 6.7624
Module Summary |4.2+j0| = 4.2
|0+j0| = 0
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 11
Program 13.10: Rect: Overloaded Constructors
#include <iostream>
Module 13
using namespace std;
Intructors: Abir
Das and class Pt { public: int x_, y_; Pt(int x, int y): x_(x), y_(y) { } }; // A Point
Sourangshu
Bhattacharya class Rect { Pt LT_, RB_; public:
Rect(Pt lt, Pt rb):
Objectives & LT_(lt), RB_(rb) { } // Cons 1: Points Left-Top lt and Right-Bottom rb
Outline Rect(Pt lt, int h, int w):
Constructor
LT_(lt), RB_(Pt(lt.x_+w, lt.y_+h)) { } // Cons 2: Point Left-Top lt, height h & width w
Contrasting with
Rect(int h, int w):
Member Functions LT_(Pt(0, 0)), RB_(Pt(w, h)) { } // Cons 3: height h, width w & Point origin as Left-Top
Parameterized int area() { return (RB_.x_-LT_.x_) * (RB_.y_-LT_.y_); }
Default Parameters };
Overloaded
int main() { Pt p1(2, 5), p2(8, 10);
Destructor Rect r1(p1, p2), // Cons 1: Rect::Rect(Pt, Pt)
Contrasting with r2(p1, 5, 6), // Cons 2: Rect::Rect(Pt, int, int)
Member Functions
r3(5, 6); // Cons 3: Rect::Rect(int, int)
Default cout << "Area of r1 = " << r1.area() << endl;
Constructor
cout << "Area of r2 = " << r2.area() << endl;
Object Lifetime cout << "Area of r3 = " << r3.area() << endl;
Automatic }
Static -----
Dynamic Area of r1 = 30
Module Summary Area of r2 = 30
Area of r3 = 30
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 12
Program 13.11/12: Stack: Destructor
Module Summary
• data leaks unless released within the scope of s • Can de-initialization be a part of scope rules?
• When to call de init()? User may forget to call • Yes. Destructor is implicitly called at end of scope
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 13
Destructor: Contrasting with Member Functions
Module 13
Destructor Member Function
Intructors: Abir
Das and
• Has implicit this pointer
• Has implicit this pointer
Sourangshu
Bhattacharya • Any name different from name of class
• Name is ˜ followed by the name of the class
class Stack { public:
Objectives & class Stack { public: int empty();
Outline ~Stack(); };
};
Constructor
• Must have a return type - may be void
Contrasting with
Member Functions
• Has no return type - not even void
int Stack::empty();
Stack::~Stack(); // Not even void
Parameterized
Default Parameters
• Does not return anything. Has no return statement
• Must have at least one return statement
Overloaded int Stack::empty()
Stack::~Stack() { return (top_ == -1); }
Destructor { } // Returns implicitly
Contrasting with • Explicit call by the object
Member Functions • Implicitly called at end of scope
s.empty(); // Calls Stack::empty(&s)
Default
Constructor
• May be public or private
• May be public or private
Object Lifetime
• No parameter is allowed - unique for the class
• May have any number of parameters
Automatic • Cannot be overloaded
• Can be overloaded
Static
Dynamic
Module Summary
Module 13
• Constructor
Intructors: Abir
Das and
Sourangshu
◦ A constructor with no parameter is called a Default Constructor
Bhattacharya ◦ If no constructor is provided by the user, the compiler supplies a free default
Objectives & constructor
Outline
◦ Compiler-provided (free default) constructor, understandably, cannot initialize the
Constructor
Contrasting with
object to proper values. It has no code in its body
Member Functions
Parameterized • Destructor
Default Parameters
Overloaded ◦ If no destructor is provided by the user, the compiler supplies a free default
Destructor destructor
Contrasting with
Member Functions ◦ Compiler-provided (free default) destructor has no code in its body
Default
Constructor
Object Lifetime
Automatic
Static
Dynamic
Module Summary
Module Summary
• User has provided a default constructor
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 16
Program 13.14: Complex: Default Constructor: Free
#include <iostream>
Module 13
#include <cmath>
Intructors: Abir using namespace std;
Das and
Sourangshu
Bhattacharya class Complex { private: double re_, im_; // private data
public: // No constructor given be user. So compiler provides a free default one
Objectives & double norm() { return sqrt(re_*re_ + im_*im_); }
Outline void print() { cout << "|" << re_ << "+j" << im_ << "| = " << norm() << endl; }
Constructor
void set(double re, double im) { re_ = re; im_ = im; }
Contrasting with
};
Member Functions int main() { Complex c; // Free constructor from compiler. Initialization with garbage
Parameterized
Default Parameters c.print(); // Print initial value - garbage
Overloaded
c.set(4.2, 5.3); // Set proper components
Destructor c.print(); // Print values set
Contrasting with } // Free destuctor from compiler
Member Functions
-----
Default |-9.25596e+061+j-9.25596e+061| = 1.30899e+062
Constructor
|4.2+j5.3| = 6.7624
Object Lifetime
Automatic
Static • User has provided no constructor / destructor
Dynamic • Compiler provides default (free) constructor / destructor
Module Summary
• Compiler-provided constructor does nothing – components have garbage values
• Compiler-provided destructor does nothing
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 17
Object Lifetime
Module 13
• In OOP, the object lifetime (or life cycle) of an object is the time between an object’s
Intructors: Abir
Das and
creation and its destruction
Sourangshu
Bhattacharya
• Rules for object lifetime vary significantly:
◦ Between languages
Objectives &
Outline ◦ in some cases between implementations of a given language, and
Constructor ◦ lifetime of a particular object may vary from one run of the program to another
Contrasting with
Member Functions • Context C++: Object Llifetime coincides with Variable Lifetime (the extent of a
Parameterized
Default Parameters
variable when in a program’s execution the variable has a meaningful value) of a
Overloaded
variable with that object as value (both for static variables and automatic variables).
Destructor
Contrasting with
However, in general, object lifetime may not be tied to the lifetime of any one variable
Member Functions
• Context Java / Python: In OO languages that use garbage collection (GC), objects
Default
Constructor are allocated on the heap
Object Lifetime ◦ object lifetime is not determined by the lifetime of a given variable
Automatic
Static
◦ the value of a variable holding an object actually corresponds to a reference to the object,
Dynamic not the object itself, and
Module Summary ◦ destruction of the variable just destroys the reference, not the underlying object
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 18
Object Lifetime: When is an Object ready?
How long can it be used?
Application Class Code
Module 13
Intructors: Abir void MyFunc() { // E1: Allocation of c on Stack Complex::Complex(double re = 0.0, // Constructor
Das and ...
Sourangshu
double im = 0.0):
Bhattacharya Complex c; // E2: Constructor called re_(re), im_(im) // E3: Initialization
... { // E4: Object Lifetime STARTS with initialization
Objectives & cout << "Ctor:" << endl;
Outline c.norm(); // E5: Use }
Constructor
... double Complex::norm() // E6 norm executes
Contrasting with { return sqrt(re_*re_ + im_*im_); }
Member Functions return; // E7: Destructor called Complex::~Complex() { cout << "Dtor:" << endl;
Parameterized } // E9: De-Allocation of c from Stack } // E8: Object Lifetime ENDS with destructor
Default Parameters
Overloaded
Module 13
• Execution Stages
Intructors: Abir
Das and ◦ Memory Allocation and Binding
Sourangshu
Bhattacharya
◦ Constructor Call and Execution
◦ Object Use
Objectives &
Outline
◦ Destructor Call and Execution
Constructor
◦ Memory De-Allocation and De-Binding
Contrasting with
Member Functions
• Object Lifetime
Parameterized
Default Parameters
◦ Starts with execution of Constructor Body
Overloaded ▷ Must follow Memory Allocation
Destructor ▷ As soon as Initialization ends and control enters Constructor Body
Contrasting with
Member Functions ◦ Ends with execution of Destructor Body
Default
Constructor ▷ As soon as control leaves Destructor Body
Object Lifetime ▷ Must precede Memory De-allocation
Automatic
Static
◦ For Objects of Built-in / Pre-Defined Types
Dynamic
▷ No Explicit Constructor / Destructor
Module Summary
▷ Lifetime spans from object definition to end of scope
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 20
Program 13.15: Complex: Object Lifetime: Automatic
Module 13
#include <iostream>
#include <cmath>
Intructors: Abir using namespace std;
Das and
Sourangshu
Bhattacharya class Complex { private: double re_, im_; public:
Complex(double re = 0.0, double im = 0.0): re_(re), im_(im) // Ctor
Objectives & { cout << "Ctor: (" << re_ << ", " << im_ << ")" << endl; }
Outline ~Complex() { cout << "Dtor: (" << re_ << ", " << im_ << ")" << endl; } // Dtor
Constructor
Contrasting with
double norm() { return sqrt(re_*re_ + im_*im_); }
Member Functions void print() { cout << "|" << re_ << "+j" << im_ << "| = " << norm() << endl; }
Parameterized };
Default Parameters Complex c(4.2, 5.3); // Static (global) object c
Overloaded
// Constructed before main starts. Destructed after main ends
Destructor int main() {
Contrasting with cout << "main() Starts" << endl; ----- OUTPUT -----
Member Functions
Complex d(2.4); // Ctor for d Ctor: (4.2, 5.3)
Default main() Starts
Constructor
c.print(); // Use static object Ctor: (2.4, 0)
Object Lifetime d.print(); // Use local object |4.2+j5.3| = 6.7624
Automatic } // Dtor for d |2.4+j0| = 2.4
Static Dtor: (2.4, 0)
Dynamic // Dtor for c Dtor: (4.2, 5.3)
Module Summary
Module 13
Intructors: Abir • Objects are initialized by Constructors that can be Parameterized and / or Overloaded
Das and
Sourangshu
Bhattacharya
• Default Constructor does not take any parameter – necessary for arrays of objects
Objectives &
• Objects are cleaned-up by Destructors. Destructor for a class is unique
Outline
• Compiler provides free Default Constructor and Destructor, if not provides by the
Constructor
Contrasting with
program
Member Functions
Parameterized • Objects have a well-defined lifetime spanning from execution of the beginning of the
Default Parameters
Overloaded
body of a constructor to the execution till the end of the body of the destructor
Destructor • Memory for an object must be available before its construction and can be released
Contrasting with
Member Functions only after its destruction
Default
Constructor
Object Lifetime
Automatic
Static
Dynamic
Module Summary