C++ Features and Constructs Ch. 3 except 3.2, 3.4, 3.9, 3.11.

Slides:



Advertisements
Similar presentations
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.
Advertisements

Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Programming Languages and Paradigms The C Programming Language.
Programmer-defined classes Part 2. Topics Returning objects from methods The this keyword Overloading methods Class methods Packaging classes Javadoc.
F UNCTION O VERLOADING Chapter 5 Department of CSE, BUET 1.
Operator Overloading Fundamentals
Object Oriented Programming COP3330 / CGS5409.  C++ Automatics ◦ Copy constructor () ◦ Assignment operator =  Shallow copy vs. Deep copy  DMA Review.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 10: Pointers by.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 7: User-Defined Functions II.
Classes: A Deeper Look Systems Programming.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Review of C++ Programming Part II Sheng-Fang Huang.
OPERATOR OVERLOADING. Closely related to function overloading is - operator overloading. In C++ you can overload most operators so that they perform special.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
The Rest of the Story.  Constructors  Compiler-generated  The Initializer List  Copy Constructors  Single-arg (conversion ctors)  The Assignment.
EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Case Study - Fractions Timothy Budd Oregon State University.
Defining and Converting Data Copyright Kip Irvine, 2003 Last Update: 11/4/2003.
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+
Chapter 6: Programmer- defined Functions Development of simple functions using value and reference parameters JPC and JWD © 2002 McGraw-Hill, Inc. Modified.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
User Defined Functions Chapter 7 2 Chapter Topics Void Functions Without Parameters Void Functions With Parameters Reference Parameters Value and Reference.
CPSC 252 Operator Overloading and Convert Constructors Page 1 Operator overloading We would like to assign an element to a vector or retrieve an element.
STRUCTURE OF A C++ PROGRAM. It is a common practice to organize a program into three separate files. The class declarations are placed in a header file.
C++ Programming Lecture 11 Functions – Part III By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Review 1 List Data Structure List operations List Implementation Array Linked List.
POINTERS Introduction to Systems Programming - COMP 1002, 1402.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
Structs and Classes Structs A struct can be used to define a data structure type as follows: struct Complex { double real, imag;} // specifying a Complex.
Constructors Initializing New Objects #include “fraction.h” int main() { float x; float y = 6.7; float z(7.2); Fraction.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
Overview Class Scope Review: Object parameters passed by value reference constant reference Friend function Overloading operator.
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Exception Handling How to handle the runtime errors.
CSE 332: C++ expressions Expressions: Operators and Operands Operators obey arity, associativity, and precedence int result = 2 * 3 + 5; // assigns 11.
Functions CMSC 202. Topics Covered Function review More on variable scope Call-by-reference parameters Call-by-value parameters Function overloading Default.
Advanced Programming in C
Constructors and Destructors
Eine By: Avinash Reddy 09/29/2016.
Chapter 7: User-Defined Functions II
Andy Wang Object Oriented Programming in C++ COP 3330
Constructor & Destructor
Chapter 10: Pointers Starting Out with C++ Early Objects Ninth Edition
User Defined Functions
Andy Wang Object Oriented Programming in C++ COP 3330
Constructors and Destructors
Chapter 7: User-Defined Functions II
COP 3330 Object-oriented Programming in C++
COP 3330 Object-oriented Programming in C++
COP 3330 Object-oriented Programming in C++
Java Programming Language
Recitation Course 0603 Speaker: Liu Yu-Jiun.
CS410 – Software Engineering Lecture #5: C++ Basics III
Andy Wang Object Oriented Programming in C++ COP 3330
Chapter 11 Classes.
Presentation transcript:

C++ Features and Constructs Ch. 3 except 3.2, 3.4, 3.9, 3.11

Scope Programs are built of nested "scopes". –Sometimes called "scope blocks" or "name spaces" Inner scopes "hide" or "shadow" outer scopes. Variables are only accessible when they are "in scope".

Kinds of scope Three main kinds of scope in C++ –Local: function or block –Class: extent of the class –File: only available within a file Also –Function scope: labels and gotos –Global scope

Scope Examples long x; float y; int z; void fn(char c, int x) {// parameter hides global x extern int z;// refer to global z double y = 3.14;// shadows global y { char y;// shadows double y from above y = c;// assigns to inner y ::y = 0.3;// assign to global y } y = y/3.0;// assign to local y z++;// increment global z }

Class Scope Class members and methods are available anywhere in the class without forward declaration (a.k.a. prototype) Examples: Vector::Vector(int x, int y) { Vector::x = x; Vector::y = y; }

New Topic: Optional Arguments Arguments to a function can be given default values. Example: int echo(int value=0) { return value; } echo(10); // returns 10 echo(); // returns 0

Optional Arguments (cont’d) Optional arguments must be at the end of the argument list When might this be useful?

New Topic: Overloading Functions Functions have signatures –A function's signature is the function's name its parameter list (types and orders) C++ allows functions with different signatures to have different definitions.

Overloading Functions Examples: int power(int a, int n); int power(double a, int n); What's a problem here?

Function Call Resolution: 1. If there's an exact match, call that version 2. Match through standard type promotions 3. Match through standard conversions 4. Match through user supplied conversions (section 8.7) 5. No match (error)

C++ is Strongly Typed. C++ is strongly typed –All variables must have a type before being used. Types must match before function calls can be allowed

Standard Promotions Promotions take types and increase their resolution Examples: –short to int –int to long –...

Standard conversions Conversions convert a variable to a different type Examples: –int to float –float to int –...

Example What happens in the following fragment: float x, a; int y; a = x + y;

C++ is Strongly Typed Types still need to match –Consider two functions like: int operator +(int lhs, int rhs); float operator +(float lhs, float rhs); –One of these must match for a = x + y;

When Does Conversion Happen? When does the compiler do this? –Arithmetic –Function calls (argument type conversion) –Return values

Explicit Type Conversion (Type Casting) In C++, casts look like: ( ) int x = int(3.14);

New Topic: More About References References can be variables as well as parameters to functions They must be initialized when declared Example: –int a; –int &ra = a;// ra is a reference to a

References (cont’d) A reference must be initialized to an "lvalue" –an lvalue is anything that can appear on the left- hand side of an assignment statement

New Topic: Read-only Variables (const) Variables can be declared read-only Example: const = ; const int forever_one = 1; Read-only variables are initialized at declaration but cannot be changed at run- time.

Read-only Parameters (const) Parameters can be read-only too. Example: int foo(const int x) {... } How does this come in handy?

New Topic: Dynamic Allocation in C++ Use operator new in place of malloc() = malloc( ); = new ; new understands about class constructors!

new [] new can be used for arrays too Example: –int * array = new int [10];

delete vs. free free( ); delete ;

Dynamic Allocation Examples int * int_ptr = new int; int * ten_ptr = new int(10); int [] int_array = new int [10]; Vector * vptr = new Vector(5, 6); // calls vector constructor! delete int_ptr; delete ten_ptr; delete [] int_prt; delete vptr;

A Longer Example: Fractions Fractions are numbers of the form: numerator/denominator Fractions have several properties: –The numerator and denominator are both integers. –The denominator cannot be 0 –Arithmetic operations are well defined for fractions.

Questions about Fractions How should a fraction be stored? –A pair of integers, numerator and denominator What operations should we support for fractions? –+, -, - (unary), etc. –, == –reduce(), print()

class Fraction { public: Fraction(); Fraction(int); Fraction(int, int); print(); Fraction operator +(Fraction); Fraction operator -(); Fraction operator -(Fraction); int operator <(Fraction); int operator >(Fraction); int operator ==(Fraction); private: int numerator, denominator; };

Constructor Considerations What if denominator is zero? –Exit the program We have three cases: –no arguments (default to 0/1) –one argument (numerator) –two arguments (numerator and denominator) Anything else?

Constructors Fraction::Fraction() { numerator = 0; denominator = 0; } Fraction::Fraction(int num) { numerator = num; denominator = 1; } Fraction::Fraction(int num, int denom) { numerator = num; if (denom == 0) exit(1); denominator = denom; }

print() Print() should print the fraction in the form numerator/denominator to stdout void print() { cout << numerator << “/” << denominator; }

Fraction Fraction::operator +(Fraction right) { Fraction answer; int left_num, right_num; left_num = right.denominator * numerator; right_num = denominator * right.numerator; answer.denominator = right.denominator * denominator; answer.numerator = left_num + right_num; return answer; }

Fraction Fraction::operator -() { Fraction answer(-numerator, denominator); return answer; }

Fraction Fraction::operator -(Fraction right) { Fraction answer; int left_num, right_num; left_num = right.denominator * numerator; right_num = denominator * right.numerator; answer.denominator = right.denominator * denominator; answer.numerator = left_num - right_num; return answer; }

An Easier Way to Subtract Fractions Fraction Fraction::operator -(Fraction right) { Fraction left = *this; return (left + -right); }

int Fraction::operator <(Fraction right) { int left_int = numerator * right.denominator; int right_int = right.numerator * denominator; return (left_int < right_int); } int Fraction::operator >(Fraction right) { int left_int = numerator * right.denominator; int right_int = right.numerator * denominator; return (left_int > right_int); }

int Fraction::operator ==(Fraction right) { Fraction left = (*this); return !(left right); }