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

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

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

C++ Basic Syntax. Wojciech Frohmberg / OOP Laboratory. Poznan University of Technology. Fields and methods

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

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

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

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

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

Short Notes of CS201

Constructor - example

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

CS201 - Introduction to Programming Glossary By

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

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

Constructors for classes

Comp 249 Programming Methodology

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.

Extending Classes (contd.) (Chapter 15) Questions:

Introduction to Programming Using Java (98-388)

Fundamentals of Programming Session 4

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

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

Inheritance and Polymorphism

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

Data Structures using OOP C++ Lecture 3

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

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Programming, numerics and optimization

CS304 Object Oriented Programming Final Term

G52CPP C++ Programming Lecture 13

Polymorphism Part 1 1

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

Fast Introduction to Object Oriented Programming and C++

6.096 Introduction to C++

(12-1) OOP: Polymorphism in C++ D & D Chapter 12. Instructor - Andrew S. O Fallon CptS 122 (April 3, 2019) Washington State University

Pointers and Terminal Control



Classes. Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT).

CS201 Some Important Definitions

Introduction Of Classes ( OOPS )

C++ (classes) Hwansoo Han

ITI Introduction to Computing II

Programming for Engineers Introduction to C

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

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

Ch. 12: Operator Overloading

Instantiation of Template class

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

INHERITANCE: EXTENDING CLASSES

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

Object Oriented Design

Object Oriented Design

OOP. Unit:3.3 Inheritance

ITI Introduction to Computing II

Object-Oriented Programming

21. Exceptions. Advanced Concepts: // exceptions #include <iostream> using namespace std;

Class object initialization block destructor Class object

Inheritance, and Polymorphism.

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming

Suppose we find the following function in a file: int Abc::xyz(int z) { return 2 * z + 1; }

by Pearson Education, Inc. All Rights Reserved.

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

Part VII. Object-Oriented Programming. Philip Blakely (LSC) C++ Introduction 194 / 370

Protection Levels and Constructors The 'const' Keyword

Programs as Models. Procedural Paradigm. Class Methods. CS256 Computer Science I Kevin Sahr, PhD. Lecture 11: Objects

Chapter 4: Writing Classes

C++ Programming: Polymorphism

6.096 Introduction to C++ January (IAP) 2009

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

COMP 110/L Lecture 19. Kyle Dewey

Advanced C++ Topics. Alexander Warg, 2017

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

Java Object Oriented Design. CSC207 Fall 2014


Advanced Systems Programming

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I

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

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

Intermediate Programming, Spring 2017*

What is Inheritance?

(5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University

CS11 Introduction to C++ Fall Lecture 7

Object Oriented Software Design II

CSC 211 Intermediate Programming. Arrays & Pointers

Object Oriented Programming. Solved MCQs - Part 2

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

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

CS304 Object Oriented Programming

Definition of DJ (Diminished Java)

IS0020 Program Design and Software Tools Midterm, Fall, 2004

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Motivation was to facilitate development of systems software, especially OS development.

Chapter 7. Inheritance

a data type is Types

Differentiate Between Keywords and Identifiers

C: How to Program. Week /Mar/05

A Deeper Look at Classes

The University of Nottingham

Transcription:

Constructors and destructors 1 1 Department of Computer Science Poznan University of Technology 2012.10.07 / OOP Laboratory

Outline 1 2 3 4 5

Outline 1 2 3 4 5

Outline 1 2 3 4 5

Outline 1 2 3 4 5

Outline 1 2 3 4 5

Constructor syntax Header file 1 //... 2 class ClassName { 3 public: 4 ClassName(); 5 //... 6 }; 7 //... Code file 1 // other libraries header files... 2 #include "header-file.h" 3 4 ClassName::ClassName() { 5 //... 6 }

Destructor syntax Header file 1 //... 2 class ClassName { 3 public: 4 ~ClassName(); 5 //... 6 }; 7 //... Code file 1 // other libraries header files... 2 #include "header-file.h" 3 4 ClassName::~ClassName() { 5 //... 6 }

Task Analyze and answer questions 1 Which from the constructions below triggers parameterless constructor and destructor invocation and which possibly causes syntax error, comment this(these) line(lines). 1 void myfunction1(classname param) { 25 if (true) { 2 //... 26 ClassName &o6 = o1; 3 } 27 } 4 void myfunction2(classname &param) { 28 if (true) { 5 //... 29 ClassName *o7; 6 } 30 } 7 //... 31 if (true) { 8 ClassName o1; 32 ClassName *o8 = o1; 9 myfunction1(o1); 33 } 10 myfunction2(o1); 34 if (true) { 11 if (true) { 35 ClassName *o9 = &o1; 12 ClassName o2; 36 } 13 o2 = o1; 37 if (true) { 14 } 38 ClassName *o10 = new ClassName; 15 if (true) { 39 } 16 ClassName o3 = ClassName(); 40 if (true) { 17 } 41 ClassName o11(); 18 if (true) { 42 delete o11; 19 ClassName o4; 43 } 20 o4 = ClassName(); 44 if (true) { 21 } 45 ClassName *o12 = new ClassName(); 22 if (true) { 46 delete o12; 23 ClassName o5 = o1; 47 } 24 } Use cout in your constructor and make use of static/global variable lineno to determine in which line constructor/destructor was invoked.

syntax Header file 1 //... 2 class ClassName { 3 // <access-modifier> 4 ClassName([const ]type [&]param1name[, type param2name = defaultvalue[,...]]); 5 // the ampersand (passing value by reference) is needed 6 // in copy constructor of the same type! 7 // possible other parameters than the first one 8 // must have assigned default value! 9 }; 10 //... Code file 1 //... 2 #include "class_name.h" 3 //... 4 ClassName::ClassName([const ]type [&]paramname[, type param2name = defaultvalue[,...]]) { 5 // the ampersand (passing value by reference) is needed 6 // in copy constructor of the same type! 7 //... 8 } 9 //...

usage is invoke in two cases 1 While initializing the variable, e.g: 1 ClassName cn = valuetocopy; // valuetocopy not necessairly have to be of type ClassName But not: 1 ClassName cn; 2 cn = valuetocopy; 2 While passing to the function/method, e.g.: 1 void myfunction(classname cn) { 2 //... 3 } 4 //... 5 myfunction(valuetocopy); // valuetocopy not necessairly have to be of type ClassName

Tasks Analyze and answer questions Analyze task code from the section with parameterless constructors and destructors and answer which from given lines cause triggering copy constructor.

declaration syntax Header file 1 //... 2 class ClassName { 3 // <access-modifier> 4 [explicit ]ClassName(type paramname[=defaultvalue[,...]]); 5 // explicit keyword prevents constructor from being interpreted as 6 // a copy constructor 7 }; Code file 1 //... 2 #include "class_name.h" 3 //... 4 ClassName::ClassName(type paramname[=defaultvalue[,...]]) { 5 //... 6 }

usage Note Once you declare any constructor with parameter the default parameterless constructor (the one generated by the compiler if no constructors are explicitly declared) will vanish, so you won t be able e.g. to declare object like this: 1 ClassName cn; Neither to inherit from the class without explicitly define constructor inheritance. Of course unless you define the parameterless constructor.

Tasks Complete the tasks 1 Create class Product with constructor taking as argument product name and its price. Create the static field aggregating prices upon instances of Product class. Each time you create the Product instance aggregate should sum its price. Similarly when the object will be destroyed its price should be subtracted. 2 Create class String with a parameterless constructor as well as copy constructor taking const char* variable as an argument that constructor should copy in case of its removal before the object destruction. Class should also be equipped with copy constructor taking a single argument of type integer, character and double value. Create an virtual method tostring that returns containing String. Remember to free the memory that was allocated in the constructor! To parse integer, char and double argument use sprintf function of stdio.h library.

About About The virtual destructor protects the program from the leak of the memory in case of usage of explicit destructors (delete) when object is treated as one of its base class. There is no such problem in case of instances created in place (to construct the object one have not used the new operator) because the type of the instance is exactly as in variable definition. 1 //... 2 class BaseClass { 3 ~BaseClass(); 4 }; 5 //... 6 class ChildClass: public BaseClass { 7 ~ChildClass(); 8 }; 9 //... 10 BaseClass *bs = new ChildClass; 11 delete bs; // BaseClass destructor will be invoked though bs points to the ChildClass!!!! Declaration syntax Just like in case of virtual methods virtual keyword should precede the destructor declaration in header file.

Task Complete the task 1 Create class Name inheriting from String class from the previous tasks. Prepare the constructor taking the first and the last name as arguments. Equip the class also with two separate setters for first name and the last name. Store the first and last name in fields of type char *. To store first value you can use derived field from the parent class. Override the tostring method to make it return the char string of format: LastName, FirstName. Use the above code to write the name to the standard output. 1 String *name = new Name("Albert", "Einstein"); 2 printf("%s\n", name->tostring()); 3 delete name; Test whether the last line of the code invokes destructor of the String class or derived Name class.

syntax Header file 1 //... 2 class ClassName [: [modificator] ParentClass] { 3 // <access-modifier> 4 ClassName(); // We can t initialize field without constructor body! 5 //... 6 }; 7 //... Source file 1 #include "class_name.h" 2 3 ClassName(): [ParentConstructor([params]), ] fieldname([constructorparam[,...]]) { 4 // single "constructorparam" can be seen as a default initializing 5 // value in case of primitive types (int, double, char *, etc.) 6 //... 7 }

Tasks Complete following tasks 1 Complete the task 1 from s section. This time use apart from inheriting from String class use two instances of String class to store the first and last name. Initialize the fields in the constructor. 2 (*) Once again complete the same task. In this approach instead of two fields of type String where you d store the first and last name try to inherit multiple times from the String class. You cannot derive directly from the same class two times. You need to create two dumb classes. The question is how to access (assumed) protected field that contain actual char string.