Constructor - example

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

C++ Classes, Constructor & Object Oriented Programming

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

DHANALAKSHMI COLLEGE OF ENGINEERING, CHENNAI DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING REWRAP TEST I CS6301 PROGRAMMING DATA STRUCTURES II

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

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

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

PESIT Bangalore South Campus

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


Data Structures using OOP C++ Lecture 3

Computer Programming with C++ (21)

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.

Introduction Of Classes ( OOPS )

CSC1322 Object-Oriented Programming Concepts

Inheritance, and Polymorphism.

Object Oriented Design

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

Developed By Strawberry

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

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:

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

Overloading operators

Cpt S 122 Data Structures. Introduction to C++ Part II

Classes - 2. Data Processing Course, I. Hrivnacova, IPN Orsay

Intermediate Programming & Design (C++) Classes in C++

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

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

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

Some important concept in oops are 1) Classes 2) Objects 3) Data abstraction & Encapsulation. 4) Inheritance 5) Dynamic binding. 6) Message passing

A Deeper Look at Classes

Programming, numerics and optimization

Function Overloading

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

C++_ MARKS 40 MIN

Lecture 5. Function Pointers

CONSTRUCTOR AND DESTRUCTOR

Object-Oriented Programming (OOP) Fundamental Principles of OOP

Functions. CS111 Lab Queens College, CUNY Instructor: Kent Chin

Lab 2: Pointers. //declare a pointer variable ptr1 pointing to x. //change the value of x to 10 through ptr1

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

Introduction to Classes

Use the dot operator to access a member of a specific object.

Preview 9/20/2017. Object Oriented Programing with C++ Object Oriented Programing with C++ Object Oriented Programing with C++

AN OVERVIEW OF C++ 1

Chapter 10 Introduction to Classes

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

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

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

A506 / C201 Computer Programming II Placement Exam Sample Questions. For each of the following, choose the most appropriate answer (2pts each).

4. C++ functions. 1. Library Function 2. User-defined Function

COEN244: Class & function templates

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

G52CPP C++ Programming Lecture 16

UNIT I DATA ABSTRACTION & OVERLOADING. Overview of C++: The compilation process

Name SECTION: 12:45 2:20. True or False (12 Points)

OBJECT ORIENTED PROGRAMMING

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

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

! A class in C++ is similar to a structure. ! A class contains members: - variables AND. - public: accessible outside the class.

C++ Memory Map. A pointer is a variable that holds a memory address, usually the location of another variable in memory.

C++ PROGRAMMING LANGUAGE: CLASSES. CAAM 519, CHAPTER 13

Classes: A Deeper Look

Midterm Exam 5 April 20, 2015

1 Short Answer (5 Points Each)

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

Chapter 13: Introduction to Classes Procedural and Object-Oriented Programming

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

W8.1 Continuing Classes friend Functions and friend Classes Using the this Pointer Cascading Function Calls

Short Notes of CS201

C++ 8. Constructors and Destructors

G52CPP C++ Programming Lecture 13

The Class. Classes and Objects. Example class: Time class declaration with functions defined inline. Using Time class in a driver.

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

Partha Sarathi Mandal

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

CPE 112 Spring 2015 Exam III (100 pts) April 8, True or False (12 Points)

Implementing Subprograms

TEMPLATE IN C++ Function Templates

CS201 - Introduction to Programming Glossary By

Programming in C++: Assignment Week 8

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Programming 2. Object Oriented Programming. Daniel POP

Functions that Return a Value. Approximate completion time Pre-lab Reading Assignment 20 min. 92

Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES III

Constructors for classes

More C++ : Vectors, Classes, Inheritance, Templates

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

2 ADT Programming User-defined abstract data types

Module Operator Overloading and Type Conversion. Table of Contents

CS304 Object Oriented Programming Final Term

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles

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

Fundamentals of Programming Session 24

Concepts (this lecture) CSC 143. Classes with Dynamically Allocated Data. List of ints w/dups (cont.) Example: List of ints with dups.

More C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com

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

Transcription:

Constructors A constructor is a special member function whose task is to initialize the objects of its class. It is special because its name is same as the class name. The constructor is invoked whenever an object of its associated class is created. It is called constructor because it constructs the values of data members of the class.

Constructor - example class add int m, n ; public : add (void) ; ------ }; add :: add (void) m = 0; n = 0; } When a class contains a constructor, it is guaranteed that an object created by the class will be initialized automatically. add a ; Not only creates the object a of type add but also initializes its data members m and n to zero.

Constructors continue There is no need to write any statement to invoke the constructor function. If a normal member function is defined for zero initialization, we would need to invoke this function for each of the objects separately. A constructor that accepts no parameters is called the default constructor. The default constructor for class A is A : : A ( )

Characteristics of Constructors They should be declared in the public section. They are invoked automatically when the objects are created. They do not have return types, not even void and they cannot return values.

Characteristics of Constructors continue They cannot be inherited, though a derived class can call the base class constructor. Like other C++ functions, Constructors can have default arguments. Constructors can not be virtual.

Characteristics of Constructors We can not refer to their addresses. continue An object with a constructor (or destructor) can not be used as a member of a union. They make implicit calls to the operators new and delete when memory allocation is required.

Constructors continue When a constructor is declared for a class initialization of the class objects becomes mandatory.

Constructors Syntax: class class_name public: class_name(); }; Example: class student int st_id; public: student() st_id=0; } };

#include <iostream> Program continue class Line private: double length; public: void setlength( double len ); double getlength( void ); Line(); // This is the constructor };

Program // Member functions definitions Line::Line(void) cout << "Object is being created" << endl; } void Line::setLength( double len ) length = len; } double Line:: getlength( void ) return length; }

Program int main( ) Line line; line.setlength(6.0); // set line length cout << "Length of line : " ; line.getlength(); return 0; }

Program Output Object is being created Length of line : 6

Constructors Pgm to create a class Addition to add two integer values. Use constructor to initialize values. Pgm to create a class Circle to compute its area. Use constructor to initialize the data members.

Types of Constructors Parameterized constructors Overloaded constructors Constructors with default argument Copy constructors Dynamic constructors

Parameterized Constructors It may be necessary to initialize the various data elements of different objects with different values when they are created. This is achieved by passing arguments to the constructor function when the objects are created. The constructors that can take arguments are called parameterized constructors.

class add int m, n ; public : add (int, int) ; ------ }; add : : add (int x, int y) m = x; n = y; } Parameterized Constructors continue When a constructor is parameterized, we must pass the initial values as arguments to the constructor function when an object is declared. Two ways Calling: o Explicit add sum = add(2,3); o Implicit add sum(2,3) Shorthand method

Program #include <iostream> using namespace std; class Line private: double length; public: }; void setlength( double len ); double getlength( void ); Line(double len); // This is the constructor

Program // Member functions definitions including constructor Line::Line( double len) cout << "Object is being created, length = " << len<< \n ; length = len; } void Line::setLength( double len ) length = len; } double Line::getLength( void ) return length; }

Program int main( ) Line line(10.0); // get initially set length. cout << "Length of line : " ; cout<<line.getlength() <<endl; // set line length again line.setlength(6.0); cout << "Length of line : " << line.getlength() <<endl; return 0; }

Program Output Object is being created, length = 10 Length of line : 10 Length of line : 6

Using Initialization Lists to Initialize Fields Line::Line( double len): length(len) } cout << "Object is being created, length = " << len << endl;

Multiple Constructors in a Class C + + permits to use more than one constructors in a single class. Add( ) ; // No arguments Add (int, int) ; // Two arguments

Multiple Constructors in a Class continue class add int m, n ; public : add ( ) m = 0 ; n = 0 ;} add (int a, int b) m = a ; n = b ;} add (add & i) m = i.m ; n = i.n ;} }; The first constructor receives no arguments. The second constructor receives two integer arguments. The third constructor receives one add object as an argument.

Multiple Constructors in a Class continue class add int m, n ; public : add ( ) m = 0 ; n = 0 ;} add (int a, int b) m = a ; n = b ;} add (add & i) m = i.m ; n = i.n ;} }; Add a1; Would automatically invoke the first constructor and set both m and n of a1 to zero. Add a2(10,20); Would call the second constructor which will initialize the data members m and n of a2 to 10 and 20 respectively.

Multiple Constructors in a Class continue class add int m, n ; public : add ( ) m = 0 ; n = 0 ;} add (int a, int b) m = a ; n = b ;} add (add & i) m = i.m ; n = i.n ;} }; Add a3(a2); Would invoke the third constructor which copies the values of a2 into a3. This type of constructor is called the copy constructor. Construction Overloading More than one constructor function is defined in a class.

Multiple Constructors in a Class continue class complex float x, y ; public : complex ( ) } complex (float a) x = y = a ; } complex (float r, float i) x = r ; y = i } ------ }; complex ( ) } This contains the empty body and does not do anything. This is used to create objects without any initial values.

Multiple Constructors in a Class continue C + + compiler has an implicit constructor which creates objects, even though it was not defined in the class. This works well as long as we do not use any other constructor in the class. However, once we define a constructor, we must also define the do-nothing implicit constructor.

Constructors with Default Arguments It is possible to define constructors with default arguments. Consider complex (float real, float imag = 0); The default value of the argument imag is zero. complex C1 (5.0) assigns the value 5.0 to the real variable and 0.0 to imag. complex C2(2.0,3.0) assigns the value 2.0 to real and 3.0 to imag.

A : : A ( ) A : : A (int = 0) constructor Constructors with Default Arguments Default constructor Default argument continue The default argument constructor can be called with either one argument or no arguments. When called with no arguments, it becomes a default constructor.

Dynamic Initialization of Objects Providing initial value to objects at run time. Advantage We can provide various initialization formats, using overloaded constructors. This provides the flexibility of using different format of data at run time depending upon the situation.

Copy Constructor A copy constructor is used to declare and initialize an object from another object. integer (integer & i) ; integer I 2 ( I 1 ) ; or integer I 2 = I 1 ; The process of initializing through a copy constructor is known as copy initialization.

Copy Constructor continue The statement I 2 = I 1; will not invoke the copy constructor. If I 1 and I 2 are objects, this statement is legal and assigns the values of I 1 to I 2, member-bymember.

Copy Constructor continue A reference variable has been used as an argument to the copy constructor. We cannot pass the argument by value to a copy constructor.

Dynamic Constructors The constructors can also be used to allocate memory while creating objects. This will enable the system to allocate the right amount of memory for each object when the objects are not of the same size.

Dynamic Constructors continue Allocation of memory to objects at the time of their construction is known as dynamic construction of objects. The memory is created with the help of the new operator.

Overloaded Constructors class Addition int num1,num2,res; float num3, num4, f_res; public: Addition(int a, int b); // int constructor Addition(float m, float n); //float constructor void add_int( ); void add_float(); void print(); };

Constructors with Default Argument class Addition int num1; int num2; int res; public: Addition(int a, int b=0); // constructor void add( ); void print(); };

Copy Constructor class code int id; public: code() //constructor id=100;} code(code &obj) // constructor id=obj.id; } };

Dynamic Constructors class Sum_Array int *p; public: Sum_Array(int sz) // constructor p=new int[sz]; } };

Destructors A destructor is used to destroy the objects that have been created by a constructor. Like constructor, the destructor is a member function whose name is the same as the class name but is preceded by a tilde. eg: ~ integer ( ) }

Destructors continue A destructor never takes any argument nor does it return any value. It will be invoked implicitly by the compiler upon exit from the program or block or function as the case may be to clean up storage that is no longer accessible.

Destructors continue It is a good practice to declare destructors in a program since it releases memory space for further use. Whenever new is used to allocate memory in the constructor, we should use delete to free that memory.

Destructor Destructors Special member function Same name as class Preceded with tilde (~) No arguments No return value Cannot be overloaded Before system reclaims object s memory Reuse memory for new objects Mainly used to de-allocate dynamic memory locations

Destructor Destructor

Example Of Destructor void Time::printTime() cout<<"the time is : "<<*hour<<":"<<*minute<<":"<<*second<<")" <<endl; } Time::~Time() delete hour; delete minute;delete second; } void main() Time *t; t= new Time(3,55,54); t->printtime(); t->sethour(7); t->setminute(17); t->setsecond(43); t->printtime(); delete t;} Destructor: used here to de-allocate memory locations Output: The time is : (3:55:54) The time is : (7:17:43) Press any key to continue When executed, the destructor is called

Programs for Implementation Pgm to create a class Complex to add two complex numbers using parameterized constructor and destructor. Pgm to create a class Complex to add two complex numbers using copy constructor and destructor. Pgm to create a class Complex to add dynamically created integer to a complex number using Dynamic constructor and destructor.