[PDF] Chapter-9 CONSTRUCTORS AND DESTRUCTORS





Previous PDF Next PDF



Lecture-3

o A class can have more than one constructor. Destructor o Called when an object is cleaned up (goes out of scope) o One class can have only one destructor.



Characteristic of Member Function

Destructor can be virtual but constructors cannot. 5.Only one destructor can be defined in the class. The destructors not have any argument. 6. The destructor 



Introduction to Classes (Chapter 13.1 – 13.12)

in the class can have different properties than object: an instance of a class in the same ... Only one destructor per class



Chapter-9 CONSTRUCTORS AND DESTRUCTORS

It is sometimes convenient if an object can initialize itself when it is first created without the need A class can have more than one constructor.



Faculty of Diploma Studies – 695

Only functions of the class can access the data of the class and they 36 Which class allows only one object to be created? A. Nuclear Family Class.



UNIT 4 CONSTRUCTORS AND DESTRUCTORS

If a class has constructor each object of that class will be initialized. 1) Constructor can take arguments but destructor didn't.



Electronic Science C and C++ Programming 32. Constructors and

A class cannot have more than one destructor. It takes no arguments and no return types can be specified for it not even void. It is called automatically by 



Introduction to C++: Part 1

are explicit versions of the default C++ constructors and destructors. ? Every class has them – if you don't define them then empty ones that do nothing will 



Object Oriented Programming Using C++

A derived class can be defined by specifying its relationship with the base Multiple inheritance: A new class is derived from more than one base class ...



Introduction to C++: Part 1

Bother references and pointers can be used to refer to objects in memory Classes can contain members ... Only one destructor per class is allowed!

Chapter9-Constructors and DestructorsII PUC,MDRPUC, Hassan

1|P a g e

Chapter-9CONSTRUCTORS AND DESTRUCTORSIntroduction:iIt is sometimes convenient if an object can initialize itself when it is first created, without the needto make a separate call tomember functions.iAutomatic initialization is carried out using special member functions called constructors.Constructors:iA Constructor is a special member function that is called automatically when an object iscreated.iThe purpose of a constructor isto mainly initialize the member variables of a class.iThe general syntax ofa the constructor in C++ is:

In the above example class declaration, classSumhas a member functionSum( )with the samename of the class and which provides initial value to its data member s.Characteristics of Constructor:iThe name of the constructor is the same as the name of the class.Example: In the above class, name of the class isSumand the function name isSum.iA Constructor, even though it is a function, has no return type, i.e. it is neithera value-returningfunction nor a void function.Example:Sum ( )function has no return type and not even void.iThe constructor should be declared in thepublicsection.iConstructors are executed automatically i.e. they are never invoked. They are executed when aclass object is created.

Important5 Marks

Chapter9-Constructors and DestructorsII PUC,MDRPUC, Hassan

2|P a g e

iA class can have more than one constructor. However all constructor of a class should have thesame name.iIt is not possible to refer to the address of the constructors.iThe constructors make implicit calls to the operator new and delete when memory allocation isrequired.iExample:Program to demonstrate how constructor is automatically executed at the time ofobject creation.#include#includeclass Student{public:Student( ){cout<<"Constructor called automatically";cout<<"at the time of objectcreation"<#includeclass Number{private:int a;public:Number ( ){cout<<"I am in theConstructor";a = 100;}void display( ){cout<<"Value of a is ="<

OUTPUT:Constructor called automatically at the time of object creationConstructor called automatically at the time of object creationConstructor called automatically at the time of object creation

Chapter9-Constructors and DestructorsII PUC,MDRPUC, Hassan

3|P a g e

};void main( ){Number N;N.display;}Need for a Constructor:iConstructors are named as constructors because they are getting called whenanobject isconstructed.iThe use of a constructor can be cleverly done especially in those problems where it is necessary toinitialize certain data members compulsorily.iInsteadof having separate member functions for initializing we can perform those operationsinside the constructor itself.iExample: A Program to find the sum of N natural numbers using a class constructor.#include#includeclass Sum{private:int n, s;public:Sum ( ){s = 0;}void readdata( ){cout<<"Enter the input limit"<>n;}void display( ){for(inti =1; i<=n; i++)s = s + i;cout<<"Sum of Natural numbers ="< Important2MarksOUTPUT:I am in the ConstructorValue of a is = 100 OUTPUT:Enter the input limit10Sum of Natural numbers = 55 Chapter9-Constructors and DestructorsII PUC,MDRPUC, Hassan

4|P a g e

Types of constructor:iConstructors are normally classified as follows:oDefault Constructors.oParameterized ConstructorsoCopy Constructors.Default Constructors:iA default constructor is a special member function which is invoked by the C++ compilerwithout any argument for initializing the object of a class.iIt is also called as zero argumentconstructors.iSome of the features of the default constructors are:oA default constructor function initializes the data member with no argument.oIt can be explicitly written in the public section of the class.oIn case, default constructor is not defined ina program, the C++ compiler automaticallygenerates it in a program.oThe purpose of the default constructor is to construct a default object of the class type.iThe general format of default constructor is as follows:SyntaxExampleclass Class_Name{public:Class_Name( ){.......}};class Number{public:Number( ){n = 0;}};iExample: Aprogramtodisplay N natural numbers using a classdefaultconstructor.#include#includeclassNumber{private:int n;public:Number( )//Default Constructor with no arguments{n= 0;}void readdata( ){

Important5 Marks

Chapter9-Constructors and DestructorsII PUC,MDRPUC, Hassan

5|P a g e

cout<<"Enter the input limit"<>n;}voiddisplay( ){for( i =1; i<=n; i++)cout<<"Natural numbers ="<< i<<"\t";}};void main( ){Sum S1;S1.readdata( );S1.display( );}iSomedisadvantages of default constructors are:oWhen many objects of the same class are created, all objects are initialized to same set ofvalues by default constructors.oIt is not possible to initialize different objects with different initial values using defaultconstructors.Parameterized Constructors:iA constructor that takes one or more arguments is called parameterized constructor.iUsing this constructor, it is possible to initialize different objects with different values.iParameterized constructors are also invoked automatically, whenever objects with arguments arecreated.The parameters are used to initialize the objects.iThe keywordinlineis used to define inline function.iThe general format of parameterized constructor is as follows:SyntaxExampleclass Class_Name{public:Class_Name( argu1, argu2....){.......}};classMAX{public:MAX(int a, int b){if (a > b)big = a;elsebig = b;}};

OUTPUT:Enter the input limit10Natural numbers = 1 2 3 4 5 6 7 8 9 10 Chapter9-Constructors and DestructorsII PUC,MDRPUC, Hassan

6|P a g e

iSome of the features of the parameterized constructors are:oThe parameterized constructors can be overloaded.oFor an object created with one argument, constructor with only one argument isinvokedand executed.oThe parameterized constructor can have default arguments and default values.Invoking Constructors:iA Constructor is automatically invoked by C++ compiler with an object declaration. Theconstructor can be invokedthrough the following methods.oImplicit CalloExplicit CalloInitialization at the time of declaration with " = " operator.Implicit Call:iAn Implicit call means the declaration of the object is followed by argument list enclosed inparenthesis.iExample: Program to initialize the data members usingimplicitdeclaration#include#includeclassnum{private:int a, b;public:num(int m, int n)//ParameterizedConstructor{a = m;b = n;}void display( ){cout<<" a = " << a <<" b = " << b;}};void main( ){num obj1(10, 20);//Implicit Callnum obj2(40, 50);//Implicit Callobj1.display( );obj2.display( );}OUTPUT:a = 10b = 20a = 40b = 50

Important5 Marks

Chapter9-Constructors and DestructorsII PUC,MDRPUC, Hassan

7|P a g e

Explicit Call:iIn explicit call, declaration of an object is followedby assignment operator, constructor name andargument list enclosed in parenthesis.iExample: Program to initialize the data members usingexplicitdeclaration#include#includeclassnum{private:int a, b;public:num(int m, int n)//ParameterizedConstructor{a = m;b = n;}void display( ){cout<<" a = " << a <<" b = " << b;}};void main( ){numobj1 = num(10, 20);//Explicit Callnum obj2 = num(40, 50);//Explicit Callobj1.display( );obj2.display( );}Initialization of object during declaration with assignment operator " = ":iThis method is used for the constructor with exactly one argument. In this method declaration isfollowed by assignment operator and value to be initialized.iExample: Program to initializeobjects using assignment operator.#include#includeclassnum{private:int a;public:num(intm)//ParameterizedConstructor{a = m;

OUTPUT:a = 10b = 20a = 40b = 50

Chapter9-Constructors and DestructorsII PUC,MDRPUC, Hassan

8|P a g e

}void display( ){cout<

OUTPUT:Object1 = 100Object2 = 200

Chapter9-Constructors and DestructorsII PUC,MDRPUC, Hassan

9|P a g e

Example:xa1;//Default Constructorxa2 = a1;//Copy ConstructoroWhen a new object is declared and existing object is passedas a parameter to it in thedeclaration, then also copy constructor is invoked.Example:xa1(100, 200);//Parameterized Constructorxa2(a1);//Copy Constructor invokedoWhen object is passed to a function using pass by value, copy constructor is automaticallycalled.oCopy constructor is invoked when an object returns a value.iExample: Program to find factorial of a number using copy constructor.#include#includeclasscopy{private:int var;public:copy(int temp){var = temp;}intcalculate( ){int fact, i;fact = 1;for( I =1; i<=var; i++)fact = fact * I;return fact;}};void main( ){int n;cout<<"Enter theNumber:";cin>>n;copy obj(n);copy cpy = obj;cout<<"Before Copying : "<< n<<"! =" <

Important5 Marks

Chapter9-Constructors and DestructorsII PUC,MDRPUC, Hassan

12|P a g e

}voidmain( ){num a;a.display( );}CHAPTER9-Constructors and DestructorsBLUE PRINTVSA (1 marks)SA (2 marks)LA (3 Marks)Essay (5 Marks)Total-01 Question-01 Question02 Question-Question No14-Question No 3307 MarksImportantQuestions5 MarksQuestion:1.What isConstructor?Give the rules for writing a constructor function.2.What is default constructor? Write a program to illustrate it.3.Explain parameterized constructor with syntax and example.4.Mention the different methods bywhich constructor are invoked. Explain anyonewith an illustrative example.5.Explain the features of copy constructor.6.Explain destructor with syntax and example.7.Write a C++ program to find the sum of the series 1+X+X2+....+Xnusingconstructor:#include#includeclass copy{private:int x, n;public:int compute;copy(int xx, int nn){x = xx;n = nn;}};

OUTPUT:In Constructor:Value of X = 100In Destructor Chapter9-Constructors and DestructorsII PUC,MDRPUC, Hassan

13|P a g e

int copy : : compute( ){int nextterm;int sum =1;nextterm = x;for (int i=1; i<=n; i++){sum= sum + nextterm;nextterm = nextterm * x;}return sum;}void main( ){int n, x;clrscr( );cout<<"Enter theX and N values"<>x >> n;copy obj ( x, n);copy cpy = obj;cout<<"Object 1: Sum of the series:" <quotesdbs_dbs14.pdfusesText_20

[PDF] a class can have only one private constructor

[PDF] a class can implement multiple interfaces java

[PDF] a class of language that is closed under

[PDF] a class that is used as the basis for inheritance is known as what type of class?

[PDF] a class's constructor usually defines

[PDF] a class's private helper methods may be called only by the class's other methods

[PDF] a climate of change manufacturing must rise to the risks and opportunities of climate change

[PDF] a clinician's guide to artificial intelligence

[PDF] a comparison of programming languages in economics

[PDF] a comprehensive french grammar pdf

[PDF] a computer science lab answers

[PDF] a concise introduction to logic 13th edition answer key chapter 1

[PDF] a concise introduction to logic 13th edition answer key pdf

[PDF] a concise introduction to logic answers

[PDF] a congruent b mod m