CONSTRUCTOR AND DESTRUCTOR

Similar documents
3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

public : int min, hour ; T( ) //here constructor is defined inside the class definition, as line function. { sec = min = hour = 0 ; }

Example : class Student { int rollno; float marks; public: student( ) //Constructor { rollno=0; marks=0.0; } //other public members };

Constructor - example

C++ 8. Constructors and Destructors

THE NAME OF THE CONSTRUCTOR AND DESTRUCTOR(HAVING (~) BEFORE ITS NAME) FUNCTION MUST BE SAME AS THE NAME OF THE CLASS IN WHICH THEY ARE DECLARED.

Recharge (int, int, int); //constructor declared void disply();

Review: C++ Basic Concepts. Dr. Yingwu Zhu

Constructors for classes

Constructors and Destructors. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Bangalore South Campus

Object Oriented Design

Classes and Objects. Class scope: - private members are only accessible by the class methods.

Lecture 18 Tao Wang 1


The mechanism that allows us to extend the definition of a class without making any physical changes to the existing class is called inheritance.

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Chapter 6 Inheritance Extending a Class

Developed By Strawberry

CSC1322 Object-Oriented Programming Concepts

CS304 Object Oriented Programming Final Term

Data type of a pointer must be same as the data type of the variable to which the pointer variable is pointing. Here are a few examples:

vinodsrivastava.com Constructor and Destructor

COMS W3101 Programming Language: C++ (Fall 2015) Ramana Isukapalli

Short Notes of CS201

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a.

CS201 - Introduction to Programming Glossary By

Ch. 12: Operator Overloading

COMS W3101 Programming Language: C++ (Fall 2015) Ramana Isukapalli

OBJ. ORI.& MULT. PROG., M.C.Q. BANK, FOR UNIT -2, SECOND YEAR COMP. ENGG. SEM-4, 2012 PATTERN, U.O.P. UNIT-2

Introduction Of Classes ( OOPS )

Interview Questions of C++

Chapter 10 Introduction to Classes

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

cout<< \n Enter values for a and b... ; cin>>a>>b;

Constructors & Destructors

Object Oriented Programming in C++ Basics of OOP

6.096 Introduction to C++ January (IAP) 2009

Programming 2. Object Oriented Programming. Daniel POP

Starting Savitch Chapter 10. A class is a data type whose variables are objects. Some pre-defined classes in C++ include int,

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

Data Structures using OOP C++ Lecture 3

Object Oriented Programming. Solved MCQs - Part 2

Classes: Member functions // classes example #include <iostream> using namespace std; Objects : Reminder. Member functions: Methods.

+2 Volume II OBJECT TECHNOLOGY OBJECTIVE QUESTIONS R.Sreenivasan SanThome HSS, Chennai-4. Chapter -1

B.Sc. (Hons.) Computer Science I B.Sc. (Hons.) Electronics. (i) Runtime polymorphism and compile time polymorphism

I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++

C++ Basic Syntax. Constructors and destructors. Wojciech Frohmberg / OOP Laboratory. Poznan University of Technology

Constructor & Classes Questions

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

Keyword this. Can be used by any object to refer to itself in any class method Typically used to

Programming, numerics and optimization

Next week s homework. Classes: Member functions. Member functions: Methods. Objects : Reminder. Objects : Reminder 3/6/2017

Module Operator Overloading and Type Conversion. Table of Contents

Pointers. Addresses in Memory. Exam 1 on July 18, :00-11:40am

Pointers, Dynamic Data, and Reference Types

PESIT Bangalore South Campus

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

STRUCTURING OF PROGRAM

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

COMS W3101 Programming Language: C++ (Fall 2016) Ramana Isukapalli

Object Oriented Software Design II

Ch02. True/False Indicate whether the statement is true or false.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING OBJECT ORIENTED PROGRAMMING CLASS : THIRD SEMESTER CSE

Object Oriented Software Design II

C++ Programming: Polymorphism

Introduction to Programming Using Java (98-388)

Fast Introduction to Object Oriented Programming and C++

Constants, References

C++ Addendum: Inheritance of Special Member Functions. Constructors Destructor Construction and Destruction Order Assignment Operator

CPSC 427: Object-Oriented Programming

Lecture 8: Object-Oriented Programming (OOP) EE3490E: Programming S1 2017/2018 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology

JAVA GUI PROGRAMMING REVISION TOUR III

CS 162, Lecture 25: Exam II Review. 30 May 2018

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat

Midterm Exam 5 April 20, 2015

Object Oriented Programming(OOP).

OBJECT ORIENTED PROGRAMMING. Ms. Ajeta Nandal C.R.Polytechnic,Rohtak

Classes: A Deeper Look

CS3157: Advanced Programming. Outline

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

AN OVERVIEW OF C++ 1

What does it mean by information hiding? What are the advantages of it? {5 Marks}

22316 Course Title : Object Oriented Programming using C++ Max. Marks : 70 Time: 3 Hrs.

Instantiation of Template class

CS201- Introduction to Programming Current Quizzes

IS0020 Program Design and Software Tools Midterm, Fall, 2004

Initializing and Finalizing Objects

Inheritance, and Polymorphism.

Object-Oriented Programming (OOP) Fundamental Principles of OOP

G52CPP C++ Programming Lecture 13

10. Abstract Data Types

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

Dr. Md. Humayun Kabir CSE Department, BUET

Topic 10: Introduction to OO analysis and design

Fundamentals of Programming Session 24

C++ Review. CptS 223 Advanced Data Structures. Larry Holder School of Electrical Engineering and Computer Science Washington State University

Distributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes

Transcription:

CONSTRUCTOR AND DESTRUCTOR 1. CONSTRUCTOR A member function with the same name as its class is called Constructor and it is used to initialize the objects of that class type with a legal initial value. 1.1 Declaration and Definition class x int i; int j,k; x() i=j=k=0; ; //constructor class x int i; Public: int j,k; x(); OR x::x() //constructor defined outside class i=j=k=0; 1.2 Special characteristics of constructors These are called automatically when the objects are created..all objects of the class having a constructor are initialized before some use. These should be declared in the public section for availability to all the functions. Return type(not even void) cannot be specified for constructors..these cannot be inherited,,but a derived class can call the base class constructor. These cannot be static. Default and copy constructors are generated by the compiler wherever required.generated constructors are public. These can have default arguments The address of a constructor cannot be taken..an object of a class with a constructor cannot be used as a member of a union. A constructor can call member functions of its class. Note:After declairing compulsory. a constructor,the initialization of the class objects becomes 2 Default Constructor

A constructor that accepts no parameter is called the default constructor.it simply allocates memory to data members of objects. Eg: class Travelplan int no_of_travellers; int no_of_buses; char place[40]; travelplan() --------- default constructor no_of_travellers=50; no_of_buses=2; strcpy(place, Agra ); ; Note: If a class has no explicit constructor defined,the compiler will supply a default constructor.declaring a constructor with arguments hides the default constructor.a constructor with default argument is equivalent to a default constructor. 3 Parameterized Constructors A constructor that takes arguments are called parameterized constructors..the parameterized constructors allow to initialize the various data elements of different objects with different values when they are created. Eg: class xyz float a; int b; char c; xyz(float x,int y,char ch)----- parameterized constructor a=x; b=y; c=ch; //remaining members; ; Note:Once we have declared a parameterized constructor,we must give initial values as arguments.if we do not do so, the compiler reports an error. Eg: xyz obj; //not valid For passing initial values while creating an object,we can select any one of the two ways: i) call the constructor implicitly eg: xyz obj(10.5,50, A ); ii) call the constructor explicitly

eg: xyz obj = xyz(10.5,50, A ); A temporary instance or temporary object is created when we make an explicit call.a temporary object resides in the memory as long as the object is referenced and after that it dies. 4 Copy constructor A Copy constructor is a constructor that defines and initializes an object with another object and it takes of the form classname(classname &). A copy constructor may be called in the following situations: 1. When an object is defined and initialized with other object of the same class. Eg: sample s1; sample s2=s1; 2. When we pass an object by value. 3. In case a function returns an object. class fun float x,y; fun(float a,float b) x=a; y=b; fun(fun &f) cout<< \ncopy constructor at work\n ; x=f.x; y=f.y; void display(void) cout<<x<< <<y<<endl; ; Note:-Initialization using a copy constructor is called copy initialization and is the task of the overloaded(=)assignment operator.a copy constructor takes references to an object of the same class as itself as a parameter. 4. Constructor Overloading Constructor overloading refers to a class having multiple constructor definitions,each having a different signature. A constructor overloading is similar to function overloading as it can also be overloaded for various combinations of parameter types. The only difference is that the overloaded function can return a value while the overloaded constructor cannot return a value. Eg:

class x private: float a,b; x() a=0,b=0; x(float r) a=r; b=10.0; x(float s1,float s2) a=s1; b=s2; ; 5. Destructors A destructor is also a member function whose name is the same as the class name but is preceded by tilde(~).a destructor is used to destroy the objects that have been created by a constructor. Note:Destructors should be declared in a program to release memory space for future utilization. 5.1 Declaration and definition The syntax for declaring the constructor is: ~ name_of _the_class().. Eg: class x private: float a,b; x() a=0,b=0; x(float s1,float s2) a=s1; b=s2; ~x( ); // Destructor ; 5.2 Special Characteristics of Destructors

1.Destructors are invoked automatically when the objects are destroyed. 2.These de_initialize each object before the objects goes out of scope. 3.No arguments and return type(even void) are permitted with destructors. 4.Destructors follow the usual access rules as other member functions. 5.These cannot be inherited. 6.Static destructors are not allowed. 7.Address of a destructor cannot be taken. 8.A destructor can call member function of its class. 9.An object of a clsss having a destructor cannot be a member of a union. SOLVED PROBLEMS 1.Differentiate between constructor and destructor function in context of classes and objects using C++ Ans : Constructor : 1. Name of the constructor functions is same as the name of the class. 2. No return type required for constructor functions. 3. Constructor functions are called automatically at the time of creation of the object. 4. Constructor can be overloaded. 5. constructor functions are defined in public. Destructor : 1. Name of the destructor is same as the name of the class preceded by tilde(~). 2. No return type required for destructor function. 3. Destructor functions are called automatically when the scope of the object gets over. 4. Destructor can not be overloaded. 5. Destructor function is defined in public. 2. What is a default constructor? How is it different from a destructor? Ans. A constructor that accepts no parameters is called the default constructor. A destructor is also a member function whose is name is the same as the class name but is preceded by tilde(~). A destructor destroys the objects that have been created by a constructor. It destroys the values of the objects being destroyed. (2 marks question each part carrying 1 mark) 1. Answer the questions (i) and (ii) after going through the following class : class Maths

char chapter [20]; int Marks [20]; Maths ( ) strcpy (chapter, ``geometery ); Marks =10; cout <<``chapter Intialised ; ~Maths ( ) //member Function 2 cout<<`` chapter over ; ; (i) Name the specific features of class shown by member function1 and member function 2 in above example? Ans : FUNTION 1: constructor OR default constructor (ii)how would Member Function 1 and Member Function 2 get get executed? Ans. Function 1 is executed or invoked automatically when an object of class Maths is created. Function 2 is invoked automatically when the scope of an object of class Maths comes to an end. OR Example : Maths S1;.. //constructor is invoked //Destructor is invoked

2.Answer the questions(i) and(ii) after going through the following class: class exam int marks; char subject[20]; Public: Exam() //function1 Marks=0; Strcpy(subject, computer ); Exam (char s[]) //function2 Marks=0; strcpy(subject, s ); Exam(int m) //function3 Marks=m; strcpy(subject, computer ); Exam (char s[],int m) //function4 Marks=m; strcpy(subject,s); ; i)which statement in c++ that would execute function3 and function 4 of class exam. ii)which feature of object oriented programming is demonstrated using function 1,function 2,function 3 and function 4 in the above class exam? ANS: (i)exam E( Computer science,40) (ii)constructor overloading 3.Answer the questions(i) and (ii),after going through the following class: class test char paper[20]; int marks; test() //function1 strcpy(paper, computer ); marks=0; test (char p[]) //function 2 strcpy(paper,p); marks=0; test(int M) //function 3 strcpy(paper, computer ); marks=m;

test (char p[],int M) //function 4 strcpy(paper, P); marks=m; ; (i)which feature of object oriented programming is demonstrated using function1,function2,function3 and function4 in the above class test? (ii)write statements in c++ that would execute function 4 in the above class test? Ans: (i) Constructor overloading (ii) test T( IT,98); Previously asked problems 1.class readbook Public: Readbook() //function-1 cout<< open the book <<endl; void readchapter() //function-2 cout<< reading chapter-1 <<endl; ~readbook() //function-3 cout<< close the book ; i)in object oriented programming,what is function-1reffered as and when does it get invoked? ii) In object oriented programming,what is function -3 reffered as and when does it get invoked? Ans: 1. Constructor, it is automatically invoked when an object is created 2. Destructor, it is automatically invoked when an object goes out of scope 2.Find the syntax errors if any. class abc int x=10; Float y; abc() Y=5; ~() ; void main() abc a1,a2; Ans: class abc int x; float y;

abc() y=5;x=10; ~abc() ; void main() abc a1,a2; 3. Consider the class: class semester int pages; semester() //function A pages=60; cout<< semester contains pages: ; void books() //function B cout<< /nbooks in the semester ; semester (int n) //function C pages=n; cout<< /n semester contains pages ; ~semester() //Function D cout<< end of semester ; ; (i) In OOPS,what does function D refers to as and when does it get invoked? (ii) In OOPS,which concept is illustrated by the function A and function C together? Write the commands to call these functions. Ans: i) Function D is invoked automatically when the scope of an object of class semester comes to an end. ii)constructor Overloading, Semester S; Semester S1(10);