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

Similar documents
Simplest version of DayOfYear

Chapter 10 Defining Classes

Structures and Classes CS 16: Solving Problems with Computers I Lecture #15

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

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

Ch 6. Structures and Classes

G52CPP C++ Programming Lecture 13

Chapter 6 Structures and Classes. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

Ch 7. Constructors and Other Tools

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

Software Design and Analysis for Engineers

Short Notes of CS201

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

CS201 - Introduction to Programming Glossary By

More class design with C++ Starting Savitch Chap. 11

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.

CLASSES AND OBJECTS IN JAVA

Absolute C++ Walter Savitch

Roxana Dumitrescu. C++ in Financial Mathematics

COMP 2355 Introduction to Systems Programming

Review. Outline. Array Pointer Object-Oriented Programming. Fall 2013 CISC2200 Yanjun Li 1. Fall 2013 CISC2200 Yanjun Li 2

Review. Outline. Array Pointer Object-Oriented Programming. Fall 2017 CISC2200 Yanjun Li 1. Fall 2017 CISC2200 Yanjun Li 2

Software Design and Analysis for Engineers

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

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

Programming 2. Object Oriented Programming. Daniel POP

Abstract Data Types. Different Views of Data:

Programming 2. Object Oriented Programming. Daniel POP

Ch. 11: References & the Copy-Constructor. - continued -

COMS W3101 Programming Language: C++ (Fall 2016) Ramana Isukapalli

Introduction Of Classes ( OOPS )

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

Operator overloading: extra examples

CS 32. Lecture 2: objects good?

CSC1322 Object-Oriented Programming Concepts

Constructor - example

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

2 ADT Programming User-defined abstract data types

SFU CMPT Topic: Classes

Where do we stand on inheritance?

Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst

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

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

III. Classes (Chap. 3)

Object Oriented Design

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.

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:

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

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

Problem Solving with C++

Interview Questions of C++

CISC 2200 Data Structure Fall, C++ Review:3/3. 1 From last lecture:

IS0020 Program Design and Software Tools Midterm, Fall, 2004

Lecture 14: more class, C++ streams

CS250 Final Review Questions

CS250 Final Review Questions


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

Object-Oriented Programming

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

CS201- Introduction to Programming Current Quizzes

CS24 Week 3 Lecture 1

PIC 10A. Lecture 15: User Defined Classes

C++ 8. Constructors and Destructors

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am

Object Oriented Design

COMS W3101 Programming Language: C++ (Fall 2015) Ramana Isukapalli

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

CPSC 427: Object-Oriented Programming

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

CS201 Latest Solved MCQs

Fundamentals of Programming Session 24

Template Issue Resolutions from the Stockholm Meeting

Fundamentals of Programming. Lecture 19 Hamed Rasifard

COMS W3101 Programming Language: C++ (Fall 2015) Ramana Isukapalli

The issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management

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

explicit class and default definitions revision of SC22/WG21/N1582 =

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

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

CS3157: Advanced Programming. Outline

C++ Constructor Insanity

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

Classes and Data Abstraction. Topic 5

CS250 Final Review Questions

Pointers. Developed By Ms. K.M.Sanghavi

CSE 303: Concepts and Tools for Software Development

Lecture 18 Tao Wang 1

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

Objects and streams and files CS427: Elements of Software Engineering

CS 247: Software Engineering Principles. ADT Design

CHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object

Come and join us at WebLyceum

C10: Garbage Collection and Constructors

Data Structures using OOP C++ Lecture 3

Introduction to Programming Using Java (98-388)

OBJECT ORIENTED PROGRAMMING USING C++

C++ : Object Oriented Features. What makes C++ Object Oriented

Object-Oriented Programming

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

Transcription:

Classes Starting Savitch Chapter 10 l l A class is a data type whose variables are objects Some pre-defined classes in C++ include int, char, ifstream Of course, you can define your own classes too A class definition says two basic things The kinds of values an object can hold A description of the member functions

Example: class DayOfYear l Decide on the values to represent l This example's values are dates such as July 4 using an integer for the number of the month Member variable month is int (Jan = 1, Feb = 2, etc.) Member variable day is int l Decide on the member functions needed l Just one member function named output in the first version of this class

Simplest version of DayOfYear class DayOfYear { public: void output(); int month; int day; }; void DayOfYear::output() { cout << "month = " << month } l Like a struct with an added method All parts public Clients access month, day directly << ", day = " << day << endl;

Notes about '::' and '.' l '::' used with classes to identify a member void DayOfYear::output() { } Also used with namespaces identifies scope Called scope resolution operator l '.' used with variables to identify object DayOfYear birthday; birthday.output( ); Object reference is passed to the method as an implicit parameter

What's wrong with DayOfYear? l Most important: data are exposed to users l Why is that a problem? l Two major reasons: No way to insure consistent object states e.g. user could birthday.month = 74; // huh? Developer can't change data names/meanings e.g. can't change int to string for month, can't save Date instead of month, day, l What's the solution (in C++)?

An access specifier: private l Private members of a class can only be referenced within the definitions of member functions (and friends later) If the program tries to access a private member, the compiler gives an error message l Private members can be data or functions Should have public set methods to change data Need public get methods to access the data l Btw: default for class is private (public for struct)

Better class DayOfYear class DayOfYear { public: void input( ); void output( ); void set(int new_month, int new_day); int get_month( ); int get_day( ); private: void check_date( ); int month; int day; }; DISPLAY 10.4

Creating and assigning (=) objects l Declaring an object creates the object DayOfYear today, tomorrow; // two objects are created on stack l Different if declaring pointers (or references) DayOfYear *soon, &r = today; // no object soon = new DayOfYear; // now object on heap l Assignment operator copies object s data r = *soon; // no new object just copy on stack // original (today) object data overwritten

Another class example: BankAccount l Has operations appropriate for a bank account (implemented with public member functions) And a private utility function l Stores an account balance and an interest rate 2 objects created

Method overloading BankAccount::set l A method's signature includes its name and its parameter list l Can overload a name like set with a different parameter list Number, types, order

More implementing BankAccount Using stream manipulators

Sample BankAccount results // excerpts from main: account1.set(123,99,3); // called with all 3 arguments account1.set(100,5); // called other version of set account1.update(); account2 = account1; Q: What if account2.update()?

Constructors l A constructor (a.k.a. ctor) is a member function Usually declared public l One is always called when an object is created l Main purpose initialize instance variables Also useful to allocate resources if needed l Constructor's name must be the name of the class l A constructor cannot return a value No return type, not even void

A BankAccount constructor l Declare in public part of class definition BankAccount(int dollars, int cents, double rate); l Implement essentially like other methods BankAccount::BankAccount(int dollars, int cents, double rate) { if ((dollars < 0) (cents < 0) ( rate < 0 )) { cout << "Illegal values for money or rate\n"; exit(1); } } balance = dollars + 0.01 * cents; interest_rate = rate;

Constructor call is automatic l May not invoke (i.e., call) it directly: account1.bankaccount(10, 50, 2); // ERROR l Instead invoke indirectly On stack: BankAccount account1(10, 50, 2); Or free store: new BankAccount(10, 50, 2); l But class must have a matching constructor e.g., BankAccount() if just new BankAccount; l Default constructor is called but oops: ERROR if explicit constructor is defined and not overloaded!

Overloading and the default ctor l l l l Another possible BankAccount ctor: BankAccount (double balance, double interest_rate); Or can have either one of the following. Why not both? BankAccount (double balance); BankAccount (double interest_rate); Also either explicitly define default ctor: BankAccount ( ); Or implicitly via default arguments in other ctors: BankAccount (double balance = 0.0); Tip: good idea to always include a default ctor even if there is no need to initialize variables So clients can: BankAccount checking, savings; Important for inheritance reasons too (a future topic)

Base/member initialization list l An initialization section in a constructor definition provides an alternative way to initialize member variables BankAccount::BankAccount() : balance(0), interest_rate(0) { } // still need a body (even if intentionally empty like this case) Can use parameter names too even if same name as member! l Note: order of initialization matches the order in which the variables are declared in the class, not their order in the list l Must use such a list for constants and reference variables (since references are always constant) Also must use to initialize private data in a base class (later topic) l Should always use for user-defined types if default ctor not appropriate to avoid extra ctor (and destructor) calls