Classes class A { ... };.

Slides:



Advertisements
Similar presentations
Chapter 4 Constructors and Destructors. Objectives Constructors – introduction and features The zero-argument constructor Parameterized constructors Creating.
Advertisements

Constructors and Destructors. Constructor Constructor—what’s this? Constructor—what’s this? method used for initializing objects (of certain class) method.
Constructor. 2 constructor The main use of constructors is to initialize objects. A constructor is a special member function, whose name is same as class.
Contents o Introduction o Characteristics of Constructor. o Types of constructor. - Default Constructor - Parameterized Constructor - Copy Constructor.
F UNCTION O VERLOADING Chapter 5 Department of CSE, BUET 1.
Derived Classes. C++ 2 Outline  Definition  Virtual functions  Virtual base classes  Abstract classes. Pure virtual functions.
OBJECT ORIENTED PROGRAMMING Instructor: Rashi Garg Coordinator: Gaurav Saxena.
Wrap Up and Misc Ying Wu Electrical & Computer Engineering Northwestern University ECE230 Lectures Series.
A RRAYS, P OINTERS AND R EFERENCES 1. A RRAYS OF O BJECTS Arrays of objects of class can be declared just like other variables. class A{ … }; A ob[4];
1 Constructors and Destructors Ying Wu Electrical Engineering & Computer Science Northwestern University ECE230 Lectures Series.
Constructors & Destructors Review CS 308 – Data Structures.
Copy Constructors Shallow Copy: –The data members of one object are copied into the data members of another object without taking any dynamic memory pointed.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
1 Classes and Objects. 2 Outlines Class Definitions and Objects Member Functions Data Members –Get and Set functions –Constructors.
Operator Overloading CS 308 – Data Structures What is operator overloading? Changing the definition of an operator so it can be applied on the objects.
Introduction to C++. Overview C++? What are references Object orientation Classes Access specifiers Constructor/destructor Interface-implementation separation.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
CSCI 383 Object-Oriented Programming & Design Lecture 13 Martin van Bommel.
Copyright  Hannu Laine C++-programming Part 3 Hannu Laine.
Learners Support Publications edited by Taranjit singh Aulakh, BGIET sangrur,CSE deptt Constructors and Destructors.
Basic Concepts of OOP in C++ Darvay Zsolt. C++ 2 Outline  The namespace and its members  The using declaration and directive  The address operator.
C++ Review (3) Structs, Classes, Data Abstraction.
1 Overloading Overloading allows a function or operator to have a different meaning depending on the type of objects it is used on. Examples: operator+
Concordia TAV 2002 Comp5421_421 Comp5421 Object Oriented Programming Using C++ Efficiently Lecture 4 (2) Tianxiang Shen Summer 2002 Department of Computer.
 Classes in c++ Presentation Topic  A collection of objects with same properties and functions is known as class. A class is used to define the characteristics.
Exception Handling. C++ 2 Outline  Throwing and handling exceptions  Exceptions of different types  The new operator and the exceptions  Re-throwing.
Object Oriented Programming (OOP) Lecture No. 8. Review ► Class  Concept  Definition ► Data members ► Member Functions ► Access specifier.
More C++ Features True object initialisation
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
Chapter 9 Classes: A Deeper Look, Part I Part II.
Data Structures Using C++1 Chapter 3 Pointers Dr. Liu.
Class and Structure. 2 Structure Declare using the keyword struct purpose is to group data Default visibility mode is public A struct doesn't have a constructor.
Data Structures Using C++1 Chapter 3 Pointers and Array-Based Lists.
CONSTRUCTOR AND DESTRUCTORS
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14: More About Classes.
Programming II Array of objects. this Using the this Pointer this Objects use the this pointer implicitly or explicitly. – this is – this is used implicitly.
Introduction to Programming Lecture 40. Class Class is a user defined data type.
Constructors & Destructors, Proxy Classes, Friend Function and example of static member.
LECTURE LECTURE 11 Constructors and destructors Copy constructor Textbook: p , 183.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
نظام المحاضرات الالكترونينظام المحاضرات الالكتروني Destructors The destructor fulfills the opposite functionality. It is automatically called when an object.
1 Classes classes and objects - from object-oriented programming point of view class declaration class class_name{ data members … methods (member functions)
1 Introduction to Object Oriented Programming Chapter 10.
Classes.  A collection of variables combined with a set of related functions MemberFunctions (methods) (methods) MemberVariables (data members) (data.
1 // SPECIFICATION FILE (dynarray.h) // Safe integer array class allows run-time specification // of size, prevents indexes from going out of bounds, //
Templates. C++ 2 Outline Function templates  Function template definition  Function template overloading Class templates  Class template definition.
Programming Reviews Lecture 1 Lecture Objectives What is Data Structure? What are Algorithms? To revise the use of pointers in relation to arrays To.
1 Class 19 Chapter 13 – Creating a class definition.
C++ Features Function Overloading Default Functions arguments Thinking about objects – relationship to classes Types of member functions Constructor and.
Introduction to C++ programming Recap- session 1 Structure of C++ program Keywords Operators – Arithmetic – Relational – Logical Data types Classes and.
Constructors and Destructors
Pointer to an Object Can define a pointer to an object:
Pointers and Dynamic Arrays
Submission Example May 14, 2018
CISC181 Introduction to Computer Science Dr
Constructor & Destructor
14.4 Copy Constructors.
Memberwise Assignment / Initialization
group work #hifiTeam
Constructors and Destructors
Introduction to Programming
9-10 Classes: A Deeper Look.
Dynamic Memory.
Recitation Course 0520 Speaker: Liu Yu-Jiun.
COP 3330 Object-oriented Programming in C++
A Deeper Look at Classes
Constructors & Destructors
9-10 Classes: A Deeper Look.
Presentation transcript:

Classes class A { ... };

Outline Constructor Destructor C++

Constructor Initialization of objects using constructors Calling the constructors if a member is an object C++

Initialization of Objects Using Constructors When an object is created a constructor is called. The name of the constructor must be the same as the name of the class. Function names can be overloaded in C++, thus a class can have multiple constructors. In this case the lists of formal parameters must be different. There is no return value for constructors, and it is not allowed to use the void keyword. C++

Example class Person { char* name; public: Person(); // default constructor Person(char* _name); Person(const Person& p); //copy //constructor ~Person(); void Display(); }; C++

Default Constructor The list a formal parameters must be empty, or if there are formal parameters then all these arguments must have a default value. If a class has a default constructor, then it is possible to define an object without giving the list of actual parameters. C++

If there is no Constructor If we don’t define a constructor, then an empty default constructor will be generated automatically. If there is at least one constructor, then no default constructor will be generated, therefore if we need one we should define it. C++

classname(const classname & object); Copy Constructor Purpose: define an object using another object of the same type. Form: classname(const classname & object); The const keyword is present because the actual parameter must not change. C++

Default Constructor Person::Person() { name = new char[1]; *name = 0; cout << "Default constructor\n"; } C++

Conventional Constructor Person::Person(char* _name) { name = new char[strlen(_name)+1]; strcpy(name, _name); cout << "Conventional constructor\n"; } C++

Copy Constructor Person::Person(const Person& p) { name = new char[strlen(p.name)+1]; strcpy(name, p.name); cout << "Copy constructor\n"; } C++

Destructor and Display Method Person::~Person() { cout << "Destructor\n"; delete[] name; } void Person::Display() { cout << name << endl; C++

The main function int main() { Person A; A.Display(); Person B("Stroustrup Bjarne"); B.Display(); Person *C = new Person("Kernighan Brian"); C->Display(); delete C; } C++

Output Default constructor Conventional constructor Stroustrup Bjarne Kernighan Brian Destructor C++

If there is no Copy Constructor If we don’t define a copy constructor, then a default copy constructor is generated which simply copies all the bytes of the data members (memberwise copy). This method gives good result if there are no pointers between the members. C++

Another main Function int main() { Person B("Stroustrup Bjarne"); B.Display(); // ... Person D(B); //the same as Person D = B; D.Display(); } If there is no copy constructor, then the destructor is called twice for the same memory location. C++

Example: MyVector The copy constructor The Sum member function The main function C++

The Class Declaration class MyVector { private: int *elem; int dim; public: MyVector(int *e, int d); MyVector(const MyVector & v); ~MyVector(); void SquareVect(); MyVector Sum(MyVector & v); void Display(); }; C++

The Copy Constructor MyVector::MyVector(const MyVector & v) { dim = v.dim; elem = new int[dim]; for(int i=0; i < dim; i++) elem[i] = v.elem[i]; } C++

The Sum Member Function MyVector MyVector::Sum(MyVector & v) { if (dim != v.dim) { cerr << "Error: different dimensions"; exit(1); } int* x = new int[dim]; C++

The Sum Member Function for(int i = 0; i < dim; i++) x[i] = elem[i] + v.elem[i]; MyVector t(x, dim); delete [] x; return t; } C++

The main Function int main() { int x[]={1, 2, 3, 4, 5}; MyVector v1(x, 5); int y[]={2, 4, 6, 8, 10}; MyVector v2(y, 5); v1.Sum(v2).Display(); // 3 6 9 12 15 } C++

Calling the Constructors if a Member is an Object An object of a class can contain other objects as data members. Example: class C { C_1 ob_1; C_2 ob_2; … C_n ob_n; }; C++

The Constructor In this case the constructor has the form: C(argumentlist) : list-of-objects The list of object has the form: ob_1(arglist_1), ob_2(arglist_2), ..., ob_n(arglist_n) where argumentlist is the list of formal parameters in class C, and arglista_i is the list of arguments of the object ob_i. C++

Example The Pair Class husband: Person wife : Person C++

The Pair Class class Pair { Person husband; Person wife; public: } C++

The Pair Class Pair(Person& thehusband, Person& thewife); Pair(char* husband_name, char* wife_name) : husband(husband_name), wife(wife_name) { } void Display(); }; C++

Constructor Definition, and the Display Method inline Pair::Pair(Person& thehusband, Person& thewife) : husband(thehusband), wife(thewife) { } void Pair::Display() { cout << "Husband: "; husband.Display(); cout << "Wife: "; wife.Display(); C++

The main function int main() { Pair XY; XY.Display(); Person A("A"); Person B("B"); Pair AB(A, B); AB.Display(); Pair UV("U", "V"); UV.Display(); } C++

Output Husband: Wife: Husband: A Wife: B Husband: U Wife: V C++

Destructor If an object is no longer used, the destructor will be executed. The name of the destructor starts with ~ and after that, the name of the class is given. There is no return value for destructors, and it is not allowed to use the void keyword. C++

Example #include <iostream> #include <cstring> using namespace std; class PrintOut { char* name; public: PrintOut(char* n); ~PrintOut(); }; C++

Constructor PrintOut::PrintOut(char* n) { name = new char[strlen(n)+1]; strcpy(name, n); cout << "Creating: " << name << endl; } C++

Destructor PrintOut::~PrintOut() { cout << "Freeing: " << name << endl; delete name; } C++

Global and local objects void MyFunction() { cout << "Calling MyFunction\n"; PrintOut local("LOCAL"); } PrintOut global("GLOBAL"); C++

The main function int main() { PrintOut* dynamic = new PrintOut("DYNAMIC"); MyFunction(); cout << "Continue the main function\n"; delete dynamic; } C++

Output Creating: GLOBAL Creating: DYNAMIC Calling MyFunction Creating: LOCAL Freeing: LOCAL Continue the main function Freeing: DYNAMIC Freeing: GLOBAL C++