0% found this document useful (0 votes)
20 views17 pages

Constructors and Destructors

This document covers the concepts of constructors and destructors in C++, including their definitions, types (default, parameterized, copy, and dynamic constructors), and their roles in object initialization and memory management. It explains how constructors can be overloaded for flexibility and how destructors are essential for resource cleanup when objects are no longer needed. Additionally, the document includes examples and exercises to reinforce understanding of these concepts.

Uploaded by

Heureuse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
20 views17 pages

Constructors and Destructors

This document covers the concepts of constructors and destructors in C++, including their definitions, types (default, parameterized, copy, and dynamic constructors), and their roles in object initialization and memory management. It explains how constructors can be overloaded for flexibility and how destructors are essential for resource cleanup when objects are no longer needed. Additionally, the document includes examples and exercises to reinforce understanding of these concepts.

Uploaded by

Heureuse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 17
Notes Unit 5: Constructors and Destructors Structure 5.1 Introduction 5.2 Constructors 5.2.1 Need for constructor 5.3 Parameterized constructors 54 Multiple constructors in a class 55 Default constructors 56 Dynamic initialization of Object 87 Copy Constructor 58 Dynamic constructor 59 Constructing Two Dimensional Arrays 5.9.1 Two Dimensional Arrays 5.10 Const Object 5411 Destructors 842. Summary 5.13 Check Your Progress 5.14 Questions and Exercises 8.18 Key Terms 8.16 Further Readings Objectives ‘Afier studying this unit, you should be able to + Understand the constructors +Learn about Defeult, copy, parameterized constructor, * Understand the concept of destructor. 5.1 Introduction In this lesson, we will discuss about classes and its implementation with special ‘emphasis on the concept of constructor and destructor, static member and This Pointer 5.2 Constructors When an object of a class is created, its member variables are in uninitialized state, loaded with any arbitrary values. itis desirable to have the member variables initialized to some legal values at the time of object creation, A-constructor is a member function of a class, having the same name as its class and which is called automatically each time an object of that class is created. It is used for initiaizing the member variables with desired intial values. Constructors and Destuetors Example: int rolino; Elcat In this code, the class student has a member function student() that will be called each time an object of this class is creatad, thereby initializing the member variables with appropriate values, 5.2.1 Need for constructor A variable (including structure and array types) in C++ may be initialized with a value at the time of its declaration, 109 Notes 110 Notes (Object Oriented Programmimg with C++ alization is claes che : j/aasegall! tant Declaration ‘A constructor is defined like any other member function. However, [thas seme name as the name of the class it belongs to ‘It does not have any return type (not even void) In this example, constructor abcabc() was defined inline. It may also be defined outline. Constructors and Destuetors Example: t /Joatline 6: In the examples given above, the constructors have been defined as a public member so that any function of any object may create this object. However, it can be defined as private or protected as well, but in those cases not all functions can create this object In later cases the object cannot be created in non-member functions but can be created only in member and friend functions Example: ned d //eone pri (/friend aes 5 d bbb ( 111 Notes 112 Notes ‘Object Oriented Programming wit C+ accassible fro% Generally, therefore, constructors are defined as public member unless otherwise there is a good reason against 5.3 Parameterized constructors Acconstructor may also have parameter(s) or arguments), which can be provided at the time of creating an object of that class actor with (parameters aa, espactiv Evidently, with parameterized constructor, the correct number and valid argument values must be passed to it at the time of object nstantiation. This can be done in two different ways in C++ ‘© Implicit call: calling the constructor without mentioning its name. ‘© Explicit call: caling the constructor by mentioning its name explicitly Example Constructors and Destuetors Implicit call to the constructor also allows one to create a temporary instance of a class that and the object thus created does not have any name. It is anonymous. It exists in the memory as long as its member(s) is(are) executing after which it is destroyed ounccicedcciy 113 Notes 114 Notes ‘Object Oriented Programming wit C+ 10) .show()# he exacution i sey the inetan C++ classes are derived data types and so they have constructor(s). Similarly, the primitive data types also have constructors. If the programmer does not supply the argument, default constructor is called else the value supplied by the programmer is used to initialize the variables of that data type. 5.4 Multiple constructors In a class Constructors Overloading are used to increase the flexibility of a class by having more number of constructor for a single class. Initializing objects by more than one constructor can be dane using overioading constructors. Example: #include class Overclass { public: intx, inty, Overclass() {x Overclass(int a) {x Oy a) Ovorclass(int a int b) (x= a; y=b:} b int main() ( Overclass A; Overclass A1(4); Overclass A2(8, 12): cout << "Overclass A's xy valuo: "<< Axx" "<< Ay<<", Constructors and Destuetors cout << "Qverclass A1's x,y value "<< AIX <<" Sec ALy <<" cout <= "Qverclass A2's x.y value , "<< ADK co", "ex ADY #include 115 Notes 116 (Object Oriented Programmimg with C+ Class factorial Notes ( Private Int Public Factorial (int number) { Nenumber } Void display () For (int 21; 1e=n; i++) { Fact=fact “; } Cout<<"w factorial } 5 Void main () { Int: Cliser 0, Cout<<"in enter the number to find its factorial Cino>x, 0 dispay () etch 0; ) 5.7 Copy Constructor A.copy constructor is a constructor of the form classname (classname & ). The compiler will use the copy constructor whenever you initialize an instance using values of another Instance of same type. 1 1 deta’ Constructors and Destuetors student st? = sti: // copy constructor used Copy constructor is called whenever an instance of same type is assigned to another instance of the same class. The copy constructor copies the data contents of the instance being assigned to the other instance member by member. If a copy constructor is not defined explcily, the compiler automatically, creates it and itis public However, the programmer may define hislher own copy constructor for the class in which case the default copy constructor becomes unavailable. A copy constructor takes a reference to an object of the same class as argument. Example: ‘Thase constructors may be used as follows: 1(5, 78.505 pelins = adent 22(s1 5.8 Dynamic constructor Dynamic constructor is used to allocate the memory to the objects at the run time. Memory is alloceted at run time with the help of ‘new operator By using this constructor, we can dynamically intalize the objects, Example: # include # include # include class str { 117 Notes 118 Notes char ‘name, intlen: public: stri) t len=0, name=newcharllons 1], } str(char*s) t lenzstrien(s) name=newcharllon+ 1], strepy(name s); x void show() { cout=«"NAME IS -="< using namespace std void swvaptint &, int 8b), intmaing) t inta swapta, b); cout <<"In main * < using namespace std int main { inte int & aref =a: ate: cout <«"The value of a is" <« aref, return 0, i a9 Constructors and Destuetors b) 10 ©) error go 7. What is the output of this program? #include using namespace std: void print (char * a) { cout << a << endl } int main () { const char * a = "Hello world’ print(const_castechar "> (a) ; return 0, q a) Hello word b) Hello ©) Word ) Compile time error 8. Identity the comect sentence regarding inequality between reference and pointer a) we can not create the array of reference. b) we can create the Array of reference ¢). We can use reference to reference d)_ none of the mentioned 9. Which of the following correctly declares an array? a) int array{10} b) int array; cc) array(10}; d)_ array array{10] 10. What is the index number of the last element of an array with 9 elements? a9 ») 8 Om) 4d) Programmer-defined 5.14 Questions and Exercises Does default constructor have any parameter? Define destructor. Define constructor What is the differance between constructor and destructor? What do you mean by static function members? Explain class constructor. 123 Notes 124 Notes (Object Oriented Programmimg with C+ 7. What is parameterized constructor 6. What is the use of multiple constructors? How objects can be inttialized dynamically. 10. Define Const object 5.15 Key Terms © Constructor: A constructor is a member function of a class, having the same name as its class and which is called automatically each time an object of that class is created, Implicit call: itis calling the constructor without mentioning its name, Explicit call: It is calling the constructor by mentioning its name expliily Constant funetion: A member function of a class in which the heading contains the reserved word const at the end © Default constructor: The constructor without parameters or @ constructor thet has dofault values for all parameters that is callad when a class objact comes into scope ina program, Check Your Progress: Answers: 1. d) null 2. ¢) Areference value once defined cannot be reassigned aa) & 4. a) Inswap 105 In main 105 8. b) Allemate name for the variable 6 b) 10 7 a) Hello word 8 a) we can not create the array of reference 2 a) 8 10. b) int arraylt0}; 5.16 Further Readings © Belagurusamy (2008) Object Oriented Programming With C++ Tata McGraw-Hill Education, ® Subhash, K U. (2010) Object Oriented Programming With C++ Pearson Education India. Ramesh Vasappanavara, Anand Vasappanavara, Gautam Vasappanavara, Pearson Education India

You might also like