lecture04: Constructors and Destructors

Similar documents
CS 225. Data Structures

CS 225. Data Structures. Wade Fagen-Ulmschneider

CS 225. Data Structures. Wade Fagen-Ulmschneider

Intermediate Programming, Spring 2017*

lecture30: Beyond CS 225

lecture09: Linked Lists

Important when developing large programs. easier to write, understand, modify, and debug. each module understood individually

Memory, Arrays, and Parameters

Introducing C++ to Java Programmers

04-17 Discussion Notes

Lecture 7. Log into Linux New documents posted to course webpage

CS93SI Handout 04 Spring 2006 Apr Review Answers

Announcements. mp3.1 extra credit due tomorrow lab quacks due Saturday night (6/29) mp3 due Monday (7/1)

CE221 Programming in C++ Part 1 Introduction

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

CSCE 110 PROGRAMMING FUNDAMENTALS

Class Destructors constant member functions

Constants, References

CS24 Week 3 Lecture 1

Object Reference and Memory Allocation. Questions:

A class is a user-defined type. It is composed of built-in types, other user-defined types and

การทดลองท 8_2 Editor Buffer Array Implementation

COMP6771 Advanced C++ Programming

Midterm Review. PIC 10B Spring 2018

04-19 Discussion Notes

Come and join us at WebLyceum

CSCI 1370 APRIL 26, 2017

Implementing an ADT with a Class

2 ADT Programming User-defined abstract data types

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

Exam duration: 3 hours Number of pages: 10

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

C++ Constructor Insanity

CSC1322 Object-Oriented Programming Concepts

G52CPP C++ Programming Lecture 13

lecture24: Disjoint Sets

PIC 10A Objects/Classes

Fast Introduction to Object Oriented Programming and C++

Slide Set 14. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CPSC 427: Object-Oriented Programming

Distributed Real-Time Control Systems. Lecture 14 Intro to C++ Part III

C++ For Science and Engineering Lecture 12

Homework 4. Any questions?

C++ Object-Oriented Programming

GEA 2017, Week 4. February 21, 2017

Linked List using a Sentinel

Class Example. student.h file: Declaration of the student template. #ifndef STUDENT_H_INCLUDED #define STUDENT_H_INCLUDED

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

lecture14: Tree Traversals

Short Notes of CS201

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

Polymorphism Part 1 1

NAMESPACES IN C++ You can refer the Programming with ANSI C++ by Bhushan Trivedi for Understanding Namespaces Better(Chapter 14)

CS201 - Introduction to Programming Glossary By

COP4530 Data Structures, Algorithms and Generic Programming Recitation 4 Date: September 14/18-, 2008

Smart Pointers. Some slides from Internet

Lab 1: First Steps in C++ - Eclipse

Computer Programming

CSCI-1200 Data Structures Fall 2018 Lecture 7 Templated Classes & Vector Implementation

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

ADTs in C++ In C++, member functions can be defined as part of a struct

Inheritance, and Polymorphism.

CSE 303: Concepts and Tools for Software Development

Laboratorio di Tecnologie dell'informazione. Ing. Marco Bertini

Chapter 10 Introduction to Classes

System Design and Programming II

University of Toronto

Lecture 14: more class, C++ streams

CPSC 427: Object-Oriented Programming

G52CPP C++ Programming Lecture 14. Dr Jason Atkin

Introduction Of Classes ( OOPS )

C++ For Science and Engineering Lecture 27

OBJECT ORIENTED PROGRAMMING

Midterm Exam #2 Spring (1:00-3:00pm, Friday, March 15)

CS11 Intro C++ Spring 2018 Lecture 1

CAAM 420 Fall 2012 Lecture 29. Duncan Eddy

2. It is possible for a structure variable to be a member of another structure variable.

Programming C++ Lecture 2. Howest, Fall 2014 Instructor: Dr. Jennifer B. Sartor

Inheritance and Polymorphism

A brief introduction to C++

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

Lab 2: ADT Design & Implementation

Object-Oriented Programming for Scientific Computing

Unified Modeling Language a case study

05-01 Discussion Notes

C++11 Move Constructors and Move Assignment. For Introduction to C++ Programming By Y. Daniel Liang

Common Misunderstandings from Exam 1 Material

G52CPP C++ Programming Lecture 16

CS 31 Discussion: Final Week. Taylor Caulfield

Distributed Real-Time Control Systems. Chapter 13 C++ Class Hierarchies

C++ Primer for CS175

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

Program template-smart-pointers-again.cc

EL2310 Scientific Programming

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

2.1 Introduction UML Preliminaries Class diagrams Modelling delegation... 4

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #1 Examination 12:30 noon, Tuesday, February 14, 2012

More About Classes. Gaddis Ch. 14, CS 2308 :: Fall 2015 Molly O'Neil

Transcription:

lecture04: Largely based on slides by Cinda Heeren CS 225 UIUC 13th June, 2013

Announcements lab debug due Saturday night (6/15) mp1 due Monday night (6/17)

Warmup: what happens? /** @file main.cpp */ void changegrade(student stu) if(stu.getgrade() == F ) stu.setgrade( A ); void main() Student s; s.setgrade( F ); while(s.getgrade() == F ) changegrade(s); /** @file student.h */ #ifndef STUDENT_H #define STUDENT_H class Student public: void setgrade(char letter); char getgrade() const; private: char grade; ; #endif

Another warmup: what happens here? PNG* allocate(size_t w, size_t h) PNG ret(w, h); return &ret; int main() PNG* image = allocate(256, 512); image->writetofile("blank.png"); delete image; return 0;

Motivation are a mechanism for running a function during an object s creation They are not explicitly called; rather, the system invokes them when required If no constructors are written, a default no-argument constructor is provided by the system Sphere s(4.0); Student joe("joe Ciurej", A ); Student chase("chase Geigle", D ); Student tom("tom Bogue", Q );

Writing constructors /** @file sphere.h */ #ifndef SPHERE_H #define SPHERE_H class Sphere public: Sphere(double newradius); void setradius(double newradius); private: double radius; ; #endif /** @file sphere.cpp */ #include "sphere.h" Sphere::Sphere(double newradius) radius = newradius; Sphere::setRadius(double newradius) radius = newradius;

A shortcut for constructors Usually, constructors just set a bunch of variables. Therefore, there is a succint syntax called an initializer list that does just that: // one-parameter constructor Sphere::Sphere(double newradius): radius(newradius) /* nothing */ // "default" constructor sets the radius to zero Sphere::Sphere(): radius(0.0) /* nothing */ // this constructor takes two arguments Sphere::Sphere(double newradius, const std::string & newcolor): radius(newradius), color(newcolor) /* nothing */ Note that we still need the braces after the function declaration even if there are no statements in the function.

Course staff is questionable What should the two-parameter constructor look like to enable the following functionality of the Student class? Student jason("jason Cho", F ); Can you write both implementations: initializer list and function body? Hint: Jason Cho is a string object.

Notes on constructors If you write any constructor, the system no longer provides a default constructor If you do not set member variables in the constructor, their values will be uninitialized...so you should always set all your member variables in the constructor!

Motivation: what happens here? /** @file sphere.h */ #ifndef SPHERE_H #define SPHERE_H /** @file main.cpp */ #include "sphere.h" void main() Sphere s(4.0); // or... class Sphere public: Sphere(double newradius); private: double* radius; ; #endif Sphere* s = new Sphere(4.0); delete s; /** @file sphere.cpp */ #include "sphere.h" Sphere::Sphere(double newradius) radius = new double(newradius);

Our first destructor /** @file sphere.h */ #ifndef SPHERE_H #define SPHERE_H class Sphere public: Sphere(double newradius); ~Sphere(); private: double* radius; ; #endif /** @file sphere.cpp */ #include "sphere.h" Sphere::Sphere(double newradius) radius = new double(newradius); Sphere::~Sphere() delete radius;

, not deconstructors are the opposite of constructors: they are run when an object on the stack goes out of scope or when an object on the heap is deleted are not explicitly called by the user; the system calls them as necessary Think of it this way: calling delete on a pointer to an object on the heap invokes the destructor If your object allocates any dynamic memory, then you need a destructor!

The Collage class /** @file collage.h */ #ifndef COLLAGE_H #define COLLAGE_H #include <iostream> #include "png.h" using namespace std; class Collage public: Collage(size_t numpics); ~Collage(); private: PNG* pics; ; /** @file collage.cpp */ #include "collage.h" Collage::Collage(size_t numpics) cout << "Created!" << endl; pics = new PNG[numPics]; Collage::~Collage() cout << "Destructed!" << endl; delete [] pics; #endif

What is printed in each of these functions? void onstack() cout << "Creating A..." << endl; Collage cola(24); cout << "Creating B..." << endl; Collage colb(12); void onheap() Collage* col = new Collage(4); delete col;

Bonus: RAII Resource Acquisition is Initialization (RAII) is a C++ idiom The constructor acquires a resource, and the destructor frees it Useful for writing exception-safe C++ code Examples: Controlling locks in multithreaded applications Opening files (acquiring file descriptors) Smart pointers Can you think of any more?