Docsity

C++ Programming – Constructors and Destructors | Complete Diploma IT Notes with Programs, Study notes of Object Oriented Programming

Partial preview of the text

Download C++ Programming – Constructors and Destructors | Complete Diploma IT Notes with Programs and more Study notes Object Oriented Programming in PDF only on Docsity!

GOVERNMENT POLYTECHNIC KOLHAPUR (Autonomous) - Information Technology Object Oriented Programming using C++ CHAPTER 4 Constructors & Destructors Corrected, Complete & Exam-Oriented Notes Based on classroom notes - rewritten in simple diploma-level English. All programs corrected for modern C++ (GCC / Visual Studio / Code::Blocks), No Turbo C++ functions like clrscr() or getch() are used, Contents: 1. Introduction | 2. Default Constructor | 3. Parameterized Constructor | 4. Initialization List | 5. Multiple / Overloaded Constructors | 6. Constructor with Default Arguments | 7. Dynamic Initialization | 8. Copy Constructor | 9. Destructor + Comparison Table, ‘Characteristics, Common Mistakes, Exam Points How to use: Read definition first -> understand example -> read program line-by-line -> run it yourself -> remember the ‘Important Points’ box. Student-prepared notes - For study purpose ‘C+s - CHAPTER 4 - CONSTRUCTORS & DESTRUCTORS Govt. Palytechnie Kalhapur (Autonomous) - IT 1 Introduction to Constructor Definition: A constructor is a special member function of a class that is executed automatically whenever a new object of that class is created. It has the same name as the class and has no return type - not even void. Why do we need a constructor? When we create an object, its data members contain garbage values. A constructor gives them a proper starting value. It is like switching ona machine - before you use it, it sets itself ready. Real-life example ‘When you open a new bank account, the bank creates your account with some initial details - account number, zero balance, your name. You do not call a separate function to ‘start’ the account. Similarly, when an object is created, the constructor automatically runs and sets its initial values. Syntax Syntax - Inside class class ClassName { public: ClassName(); // Constructor declaration i ‘Syntax - Outside class ClassName::ClassName () { // initialization code } Program 1 - Simple Constructor ‘C+ - CHAPTER 4 - CONSTRUCTORS & DESTRUCTORS Govt. Polytechnic Kolhapur (Autonomous) - IT 2 Default Constructor Definition: A default constructor is a constructor that takes no arguments (or all arguments have default values). It is called when an object is created without any values. Program 2 - Default Constructor Program 2 - Default Constructor finelude using namespace std; class Student { public: Student () { rollNo = 0; marks = 0; eout << "Default constructor called” << endl; } void display () { cout << "Rell No ; " << rellNe << endl; cout << "Marks : " << marks << endl; } private: int rollNo; float marks; Ve int main() { Student s1; si.display (ij return 0} Expected Output Default constructor called Roll No : 0 Marks : 0 Important Points - 1, Created as Student s1; - no brackets. Writing Student s1(); is a mistake: compiler treats it as function declaration. 2. If you write ANY other constructor, compiler will NOT give you a default constructor automatically. Gis - CHAPTER 4 - CONSTRUCTORS & DESTRUCTORS 3 Parameterized Constructor Govt. Polytechnic Kolhapur (Autonomous) - IT Definition: A parameterized constructor is a constructor that takes one or more arguments. It is used to assign initial values to an object at the time of its creation. Program 3 - Parameterized Constructor Program 3 - Parameterized Constructor finclude using namespace std; class Line { public: void setLength (double len); double getLength(); Line (double len); private: double length; vw Line::Line (double len) { cout << "Object is being created, length = " << len << endl; length = len; } void Line::setLength(double len) ( length = len; double Line::getLength() { return length; } int main() { Line line (10.0); cout << "Length of line : " << line.gethength() line.setLength (6.0); cout << "Length of line : " << line.getLength() return 0; Expected Output Object is being created, length = 10 Length of line ; 10 Length of line : 6 Exam Point - << endl; << endl; Default takes no argument and gives fixed values (e.g. 0). Parameterized takes arguments and gives different values to different objects. ‘(Crs - CHAPTER 4 - CONSTRUCTORS & DESTRUCTORS Govt. Polytechnic Kolhapur (Autonomous) - IT 5 Multiple / Overloaded Constructors Definition: When a class has more than one constructor with different numbers or types of parameters, it is called constructor overloading. Compiler selects correct constructor based on arguments passed. Program 5 - Overloaded Constructors. Program 5 - Constructor Overloading finclude using namespace std; class Employee { public: Employee() { a = 0; b = 0; } Employee (int x) { a = x; b = x; } Employee(int x, int y) { a ae b= y; } void display() { cout << "a=" << a <<" private: int a, b; Vi int main() { Employee el; Employee e2(10); Employee e3(10, 20); el.display(); e2-display(); e3.display(); return 0; Expected Output aed, bao 10, b = 10 a= 10, b = 20 w 0 How compiler decides Employee e1; -> no argument -> first constructor. Employee e2(10); -> one integer -> second constructor. a) "<< b << endl; } Employee e3(10, 20); -> two integers -> third constructor. Common Mistake - If two constructors have same number and same types of parameters, it is NOT overloading - it is an error. ‘(Gre - CHAPTER 4 - CONSTRUCTORS & DESTRUCTORS Govt. Polytechnic Kolhapur (Autonomous) - IT 6 Constructor with Default Arguments Definition: A constructor can be defined with default values for one or more parameters. If caller omits those arguments, default values are used. If caller provides values, they override defaults. Example: Complex(float real, float imag = 0); - Complex(5.0) means real=5.0, imag=0. Complex(5.0, 4.5) means real=5.0, imag Program 6 - Default Arguments. Program 6 - Default Arguments finclude using namespace std; class Complex { public: Complex (float r, float i = 0.0) { real = r; image = 4; } void show() { cout << "Real : " << real << endl; cout << "Imaginary : " << image << endl; ) private: float real, images Me int main() { Complex c1(2.3); Complex ¢2(2.3, 3.4); cl.show(); c2.show(); return 0; Expected Output Real : 2.3 Imaginary : 0 Real : 2.3 Imaginary : 3.4 Rules Default arguments must be from right to left. (float r = 0, float i) is error. Correct is (float r, float i = 0). Do not write both Complex() and Complex(float r = 0, float i = 0) together - ambiguity. ‘C+ - CHAPTER 4 - CONSTRUCTORS & DESTRUCTORS Govt. Palytechni¢ Kalhapur (Autonomous) - IT 8 Copy Constructor Definition: A copy constructor creates a new object by initializing it with an existing object of same class. It copies values of one object into another. Syntax Syntax - Copy Constructor ClassName (const ClassName sob) { // copy each member from ob} } When is copy constructor called? When one object is initialized from another: Line line2 = line1; When an object is passed by value to a function: display(line); When a function returns an object by value. Why const & ? Reference (&) avoids infinite copying. const prevents changing source object. (C++ - CHAPTER 4 - CONSTRUCTORS & DESTRUCTORS Program 8 - Copy Constructor #include using namespace std; class Line { public: Line (int len); Line(const Line sob ~Line(); int getLength(); private: int *ptr; i Line: { ne(int len) cout << "Normal constructor allocating ptr” ptr = new int; *ptr = len; } Line: { rLine (const Line obj) << endl; cout << "Copy constructor allocating ptr." << endl; ptr = new int; *ptr = *obj.ptr; } Line: Line () { cout << "Freeing memory!" << endl; delete ptr; int Lines:getLength() { return *ptr; } void display (Line obj) { cout << "Length of line : " << obj.getLength() int main{) { Line linel(10); Line line2 = linel; display (1ine1) ; display (line2); return 0; Expected Output Normal constructor allocating ptr Copy constructor allocating ptr. Copy constructor allocating ptr. Length of line : 10 Freeing memory! Copy constructor allocating ptr. Length of line : 10 Freeing memory! Freeing memory! Freeing memory! Shallow vs Deep Copy << endl; } Govt. Polytechnic Kolhapur (Autonomeus) - IT Shallow copy: copies address. Two objects share same memory. Dangerous. Deep copy: creates new memory and copies value. Safe. Program 8 does deep copy. C++ - CHAPTER 4 - CONSTRUCTORS & DESTRUCTORS Govt. Polytechnic Kolhapur (Autonomous) - IT Constructor vs Destructor - Comparison Table Pe Constru estructor Purpose Initializes an object, sets initial Cleans up, releases resources values Name Same as class name Same as class name with ~ prefix Return type No return type No return type Parameters Can have parameters. No parameters Overloading Can be overloaded Cannot be overloaded (only one) When called When object is created When object goes out of scope / deleted How many? Can be many in one class Only one per class Example Line() , Line{double) ~Line()