C++: Const Function Overloading Constructors and Destructors Enumerations Assertions

Similar documents
Memory Leak. C++: Memory Problems. Memory Leak. Memory Leak. Pointer Ownership. Memory Leak

Short Notes of CS201

CS201 - Introduction to Programming Glossary By

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

Introduction to Programming Using Java (98-388)

Francesco Nidito. Programmazione Avanzata AA 2007/08

CS 485 Advanced Object Oriented Design. Enum. Spring 2017

Common Misunderstandings from Exam 1 Material

Object Oriented Design

Programming in C. What is C?... What is C?

Programming in C UVic SEng 265

Programming in C. What is C?... What is C?

C++ (Non for C Programmer) (BT307) 40 Hours

QUIZ. What is wrong with this code that uses default arguments?

AIMS Embedded Systems Programming MT 2017

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

Programming in C and C++

12 CREATING NEW TYPES

Object-Oriented Principles and Practice / C++

C++ C and C++ C++ fundamental types. C++ enumeration. To quote Bjarne Stroustrup: 5. Overloading Namespaces Classes

Software Design and Analysis for Engineers

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 12: Classes and Data Abstraction

CSCE 314 Programming Languages

For each of the following variables named x, specify whether they are static, stack-dynamic, or heapdynamic:

Advanced Systems Programming

Programming in Haskell Aug-Nov 2015

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

double d0, d1, d2, d3; double * dp = new double[4]; double da[4];

Tokens, Expressions and Control Structures

C# Fundamentals. Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh

Absolute C++ Walter Savitch

C# Types. Industrial Programming. Value Types. Signed and Unsigned. Lecture 3: C# Fundamentals

Chapter 18 - C++ Operator Overloading

void fun() C::C() // ctor try try try : member( ) catch (const E& e) { catch (const E& e) { catch (const E& e) {

Stream Computing using Brook+

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

Industrial Programming

III. Classes (Chap. 3)

CSE 333. Lecture 11 - constructor insanity. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington

C++11: 10 Features You Should be Using. Gordon R&D Runtime Engineer Codeplay Software Ltd.

Lecture 18 Tao Wang 1

Problem Solving with C++

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

C++ 8. Constructors and Destructors

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

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

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?

7.1 Optional Parameters

C:\Temp\Templates. Download This PDF From The Web Site

class Polynomial { public: Polynomial(const string& N = "no name", const vector<int>& C = vector<int>());... };

Constants, References

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Implementing an ADT with a Class

Name: Username: I. 20. Section: II. p p p III. p p p p Total 100. CMSC 202 Section 06 Fall 2015

CS2141 Software Development using C/C++ C++ Basics

CS201 Some Important Definitions

Chapter 10 Introduction to Classes

CS201 Latest Solved MCQs

Review for Test 1 (Chapter 1-5)

Introduction. Primitive Data Types: Integer. Primitive Data Types. ICOM 4036 Programming Languages

Introduction To C#.NET

Ch. 12: Operator Overloading

Instantiation of Template class

Final CSE 131B Spring 2004

CS3215. Outline: 1. Introduction 2. C++ language features 3. C++ program organization

Lecture 3: C Programm

Engineering Tools III: OOP in C++

Class Vector: Interface CSE 143. Dynamic Memory In Classes [Chapter 4, p ] Vector Implementation. Many Ways to Implement. Draw the picture!

C++ (classes) Hwansoo Han

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

QUIZ. Can you find 5 errors in this code?

QUIZ. What are 3 differences between C and C++ const variables?

static CS106L Spring 2009 Handout #21 May 12, 2009 Introduction

The pre-processor (cpp for C-Pre-Processor). Treats all # s. 2 The compiler itself (cc1) this one reads text without any #include s

Implementing Abstractions

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

MaanavaN.Com CS1203 OBJECT ORIENTED PROGRAMMING DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

ADTs & Classes. An introduction

CS304 Object Oriented Programming Final Term

Introduction Primitive Data Types Character String Types User-Defined Ordinal Types Array Types. Record Types. Pointer and Reference Types

Assumptions. History

CSE 143. Linked Lists. Linked Lists. Manipulating Nodes (1) Creating Nodes. Manipulating Nodes (3) Manipulating Nodes (2) CSE 143 1

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language

W8.2 Operator Overloading

C Programming. Course Outline. C Programming. Code: MBD101. Duration: 10 Hours. Prerequisites:

COMP 2355 Introduction to Systems Programming

CS3157: Advanced Programming. Outline

Object-Oriented Programming

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

CIS 190: C/C++ Programming. Classes in C++

C++ For Science and Engineering Lecture 27

ComS 228 Exam 1. September 27, 2004

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

Fundamental Concepts and Definitions

An Introduction to C++

a data type is Types

Introduction to C++ with content from

ARRAYS(II Unit Part II)

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.

Padasalai.Net s Model Question Paper

Transcription:

C++: Const Function Overloading Constructors and Destructors Enumerations Assertions

Const const float pi=3.14159; const int* pheight; // defines pointer to // constant int value cannot be changed // pointer can be changed!! const int* pheight const = &ht; // both // value and pointer cannot be changed const float& PI = pi; // ref to a constant

Const in functions class house { public: float Area () const; // method does not change object void ConstructionInfo (const string builder, const Date& d); // arguments cannot be modified } Compiler will enforce restrictions Propagation of const: const method cannot invoke non-const methods Cannot pass const objects received unless receiver promises not to modify them

Function prototypes Every function call must have a prototype that the compiler has seen earlier bool strcmp (const char*, const char*); This includes system library functions Man page for system calls includes header file to be included to get prototype Including class header file provides prototype for all its methods

Function overloading Class may include several methods with same name, as long as parameter types are different class Shape { public: void Draw (); // default draw void Draw (Screen*); // draw on screen void Draw (int x, int y); // draw at position void Draw (bool reversecolours); } Not enough to have different return types Call argument types determine which method gets called (note possibility of type conversions)

Constructor A constructor for a class is called when an object of that class is created: Local / Stack Based Foo F (3, 4, Joe ); On Free Store Foo *Fptr (new Foo ((3, 4, Joe )); Anonymously goo.bar (Foo (3, 4, Joe ), moo, poo);

Constructor Constructors have the same name as the class. Constructors do not return a value. The constructor, like all functions, can be overloaded with each constructor having a different set of parameters.

Constructor class Date { private: int d, m, y; public: Date (int day, int month, int year); Date (int day, int month); Date (int day); Date (); // today s date Date (string date); }

Constructor Date::Date (int day, int month, int year) : d (day), m (month), y (year) {} The : syntax provides initializers for use during object construction Body of constructor executed after construction

Default Constructor Constructor with no arguments is a default constructor Some compilers may supply one automatically May get invoked to create temporaries More often, temporaries will be created using copy constructor (see later)

Constructor Default Constructor Constructor with no arguments. Foo F; If a class defines constructors but no default constructor, compiler will generate an error. If no constructors are defined for a class, the compiler will generate a default constructor.

Constructor Copy Constructor Initializes an object based on the contents of another object of the same type. Date (const Date &D) : d (D.d), m (D.m), y (D.y) {} Object has access to non-public members of objects of the same class

Constructor Copy Constructor Called when: A declaration is made with initialization from another object Date d1 (d2); Parameters are passed by value. An object is returned by a function.

Constructor Copy vs. Assignment operator= is called when an assignment is made Date d1 (10, 2, 2002); Date d2; d2 = d1; // operator= called However, If an assignment is made during a variable declaration, then the copy constructor rather than the assignment operator is called Date d1 = d2; // Copy NOT assignment!

Constructor Copy Constructor If no copy constructor is defined for a class, the default copy constructor is used. Member by member copy of data from one object to another. Can be troublesome if class have pointers as data members. Same issues as with the default assignment operator!!!!

Automatic Type Conversion C++ will use constructors to perform automatic type conversion void foo (Date d); Accidentally call foo(5); Since Date has a constructor Date (int day); C++ will call this method to create a Date from 5, and pass it to foo() Causes nasty bugs!

Constructor Summary Date d1(3, 10, 2002); // constructor called Date d2, d5; // default constructor called Date d3 (d2); // copy constructor called Date d4 = d1; // copy constructor called d5 = d2; // assignment operator called. Questions?

Constructor Important safety tips: If your constructors perform any non-trivial work (e.g. memory allocation), should define the full suite of: Constructors Copy constructor operator=

Destructor A destructor for a class is called when the memory of an object of that class is reclaimed: A global (static) object is reclaimed when the program terminates. A local (automatic) object is reclaimed when the function terminates (stack is popped). A dynamically allocated object is reclaimed when someone invokes the delete operator on it. Like Java finalize

Destructor void afunction (Foo f) { } Foo f2; Foo *fooptr = new Foo();... delete fooptr; // destructor called // after function is complete, destructor called on f and f2

Destructor Destructors have the same name as the class but preceded with a ~. Destructors do not return a value. Destructors take no arguments and cannot be overloaded. Destructors are used for cleaning up object data / state Allocated memory Close files Close network connections, etc.

Destructors class Foo { private: int *array_member; int asize;... public: Foo (int size); ~Foo (); }

Destructors Foo::Foo (int size) : asize (size), array_member (new int[size]) { for (int i=0; i<size; i++) array_member[i] = 0; } Foo::~Foo () { // cleanup what was allocated by // constructor if (array_member!= 0) delete array_member; }

Destructors Questions?

Enumerated Types An enumeration is a type that can hold a set of values defined by the user. Once defined, they can be used like an integer type. enum statement assigns sequential integer values to names and provide a type name for declaration.

Enumerated Types enum TrafficLightColor {RED, YELLOW,GREEN}; TrafficLightColor x; x = YELLOW;

Enumerated Types It's possible to control the values that are assigned to each enum constant. enum Day {MON=1, TUE, WED, THU, FRI, SAT, SUN}; WED == 3 enum DayFlag {MON=1, TUE=2, WED=4, THU=8, FRI=16, SAT=32, SUN=64};

Enumerated Types Enums are types, not just integers enum TrafficLightColor {RED, YELLOW, GREEN}; enum Gender {MALE, FEMALE}; TrafficLightColor x;... x = YELLOW; // good x = FEMALE; // error x = 2; // error

Enumerated Types Enums can be placed in the scope of a class: class Calendar { public: enum Day {MON=1, TUE, WED, THU, FRI, SAT, SUN};... } Calendar::Day x; x = Calendar::SAT;

Enumerated Types Questions?

Assertions Debugging mechanism to check condition at a given point in the code If condition is false, then program will abort with an error message Very useful for detecting coding errors and wrong assumptions

Assertions #include <cassert> void f (int *p) { // At this point p should be non-null assert (p!=0); }

Assertions Used for debugging Can be turned off Removing does not affect how the program works CC DNDEBUG foo.c

Assertions When to use Test preconditions Test postconditions At this point x should be equal to We should never reach this line Zero cost, adds to readability (documents assumptions) Great coding practice!

Summary Constructors Copy Constructor Default Constructor Destructor Enum Assertion Questions?