PIC 10A Objects/Classes
|
|
- Alfred Heath
- 6 years ago
- Views:
Transcription
1 PIC 10A Objects/Classes Ernest Ryu UCLA Mathematics Last edited: November 13, 2017
2 User-defined types In C++, we can define our own custom types. Object is synonymous to variable, and class is synonymous to type. The words variable and type connote the subject is a built-in type. The words object and class connote the subject is a user-defined type. Object oriented programming is the style of programming that focuses around objects. 2
3 Struct A struct is a user-defined composite type. It is a collection of data members. struct student { string firstname ; string lastname ; int UID ; ; This example has 3 data members. 3
4 Member access operator The member access operator. is used to access members of a struct. int main () { student s1; s1. firstname = " Ernest "; s1. lastname = " Ryu "; s1. UID = ; student s2 = s1; s2. firstname = " Elizabeth "; s2. UID = ; cout << s2. firstname << " " << s2. lastname << " has UID " << s2. UID << endl ; The output is Elizabeth Ryu has UID
5 Struct You can view a struct as a chunk of data. It s more convenient to use student s1 than to use string s1firstname, string s1lastname, and int s1uid separately. structs are the precursors of classes. structs are C-style while classes are C++-style. 5
6 Class A class is a more sophisticated, C++-style struct. You declare classes with class class_name { public: data members; member functions; ; For the moment, don t worry about the public keyword. 6
7 Syntax warning: semicolon after class You need a semicolon at the end of struct and class definitions. struct student { ; class complex { ; Don t forget the semicolon. 7
8 Data members Data members, also called fields, of a class are just like data members of a struct. class complex { public : double real, imag ; ; (The C++ standard library complex provides a complex number class, but we ll create our own.) 8
9 Member functions classes can also have member functions, also called methods. class complex { public : double real, imag ; void disp () { // a member function cout << real << " +" << imag << " i" << endl ; ; 9
10 Member functions Access member functions with the member access operator. int main () { complex c1; c1. real = 0.1 ; c1. imag = 2; c1. disp (); // output i 10
11 Member functions You can declare and define member functions separately. class complex { public : double real, imag ; void disp (); // declaration ; void complex :: disp () { // definition cout << real << " +" << imag << " i" << endl ; In the definition, refer to the function name with classname::funcname. 11
12 Member functions Member functions have access to data members of the object it belongs to. Member functions often cause side effects through modifying data members. :: is the scope resolution operator. We will discuss it is more detail when we talk about namespaces. You can view classes as the collection of data members accompanied by useful member functions. 12
13 Member functions with return values Member functions, like any function, can have return values. class complex { public : double real, imag ; void disp (); double magnitude (); ; double complex :: magnitude () { return sqrt ( real * real + imag * imag ); int main () { complex c1; c1. real = 3; c1. imag = 4; cout << c1. magnitude () << endl ; // output 5 13
14 Member functions with return values The return type of an member function can be the class itself. class complex { public : double real, imag ; complex add ( complex a); ; complex complex :: add ( complex a) { complex val ; val. real = real + a. real ; val. imag = imag + a. imag ; return val ; 14
15 Member functions with return values Let s see how to use a member function int main () { complex c1; c1. real = 1.1 ; c1. imag = 0; complex c2; c2. real = 2.2 ; c2. imag = 1.2 ; complex c3 = c1.add (c2 ); c3. disp (); // output i cout << typeid (c1.add (c3 )). name () << endl ; // output class complex (c1.add (c3 )). disp () // output i 15
16 this pointer The this pointer is a pointer of type class_name* and it points to the object the member function belongs to. class complex { public : complex add ( complex a); complex add_ equals ( complex a); ; complex complex :: add_ equals ( complex a) { * this = add (a); return * this ; 16
17 this pointer int main () { complex c1; c1. real = 1.1 ; c1. imag = 0; complex c2; c2. real = 2.2 ; c2. imag = 1.2 ; c1. add_equals (c2 ); c1. disp (); // output i 17
18 Constructor The following initialization is a bit cumbersome. complex c1; c1. real = 1.1 ; c1. imag = 0.2 ; Use constructors to simplify initialization. 18
19 Construtor A constructor is called when the object is created. class complex { public : // a constructor with 2 inputs complex ( double r, double i); ; int main () { complex c1(1.1, 0.2 ); c1. disp (); // output i complex :: complex ( double r, double i) { real = r; imag = i; // constructor definition Declaration and initialize together with a constructor. 19
20 Default constructor When an object is created with no inputs, default constructor is called. class complex { public : complex (); // default constructor complex ( double r, double i); ; int main () { complex c1; // default constructor called complex :: complex () { // do nothing 20
21 Implicitly defined default constructor When no constructors are provided, the compiler implicitly defines a trivial default constructor. The trivial default constructor does nothing. 21
22 So the class Implicitly defined default constructor class complex { public : double real, imag ; void disp (); ; void complex :: disp () { is the same class as class complex { public : double real, imag ; complex (); // default constructor void disp (); ; void complex :: disp () { complex :: complex () { // trivial default constr 22
23 Implicitly defined default constructor However, the class class complex { public : double real, imag ; void disp (); complex ( double r, double i); ; void complex :: disp () { complex :: complex ( double r, double i) { does not have a default constructor. 23
24 Do you need the default constructor? You need the default constructor if you plan to use arrays of the class. int main () { // default constr called for all 10 objects complex c_arr [10 ]; // pointer to an object of class complex complex * c_p ; // default constr called for all 20 objects c_p = new complex [ 20 ]; delete [] c_p ; 24
25 Constructors Often it makes sense to have several constructors. class complex { public : double real, imag ; complex (); complex ( double r); complex ( double r, double i); ; complex :: complex () { complex :: complex ( double r) { real = r; imag = 0.0 ; complex :: complex ( double r, double i) { real = r; imag = i; 25
26 Type conversion Type casting an object of class T1 into an object of class T2 is really just calling a constructor. class complex { public : double real, imag ; complex (); complex ( double r); // this constructor called complex ( double r, double i); ; int main () { (( complex ) 2.2 ). disp (); // output i 26
27 Type conversion Think of double d1 = static_ cast < double >( 2); as calling double :: double ( int i) { On the other hand, string s = string ( a ); // error fails because there is no constructor that looks like string :: string ( char c) { 27
28 Type conversion In the pointers lecture, I said the cast from T1 to T2 succeeds if there is a suitable way. The suitable way is a constructor. If there is a constructor with signature T2(T1 it is called. t); If there is a constructor that can be called after implicit conversion, it is called. For example, int i = 5; complex c1 = complex ( i); // calls complex ( double d); Otherwise the compiler fails. 28
29 Function style cast You can have multiple inputs when using the function style cast. complex ( 2.2,0.3 ). disp (); // output i cout << typeid ( complex (0,0 )). name () << endl ; // output class complex complex c1( 0.0, -0.1 ); // object has name c1 View the function style cast as directly calling the constructor without giving a name to the object. 29
30 Initializing objects with style There s often more than 1 way to initialize an object. // call 1 constructor complex c1(1.2,2.2 ); This is shorter and faster. // call 2 constructors and then copy complex c2 = complex ( 1.2, 2.2 ); This is more readable and therefore is in better style. 30
31 Syntax warning: default constructor When calling the default constructor, don t use parentheses. complex c1; // default constr complex c2( 2.2 ); // non - default constr complex c3( 2.2, 3.3 ); // non - default constr // c4 is a func with no inputs // and return type complex ( declared not defined ) complex c4 (); c4. disp (); // error. c4 is a function This is terrible, but it s just how C++ is. 31
32 Syntax warning: default constructor When using new, you may or may not use parentheses to call the default constructor. complex * c1 = new complex ; // default constr complex * c2 = new complex (); // default constr complex * c3 = new complex ( 2.2 ); // non - default complex * c4 = new complex ( 2.2,3.3 ); // non - default delete c1; delete c2; delete c3; delete c4; When T is a class, new T and new T() are (almost) the same: they both call the default constructor. 32
33 Syntax warning: default constructor When directly calling constructors through function style casts, you must use parentheses to call the default constructor. complex (). disp (); // undefined output complex ( 2.2 ). disp (); // output i complex ( 2.2,3.3 ). disp (); // output i complex. disp (); // error ( complex ). disp (); // error 33
34 Private members Private data members or member functions can only be accessed by member functions of the object. Public data members or member functions can be accessed from the outside as well. class complex { private : double real, imag ; public : complex ( double r, double i); void setreal ( double r) { real = r; double getreal () { return real ; ; int main () { complex c1(2.2,3.5 ); c1. real = 1.2 ; // error 34
35 Private data members By making data members private, user must interact with the them through the provided public methods. This forces the user to use the object in a certain way. In C++, data members are more often private than public. When data members are public, users can directly write to them. This is not safe. The class complex doesn t really benefit from private data members. The classes in hw8 do benefit from private data members. 35
36 Private member functions Member functions can also be private. You can t call a private member function from the outside. I.e., you can t do c1. disp (); if disp is private. Helper functions are functions intended to aid other functions but not intended to be used by themselves. Helper functions should be private. 36
37 Why private? Achieve modular programming by hiding as much information as possible (by making members private). A well-written class provides a simple interface to the user while hiding its complex inner workings. Control how to use the class through providing certain public members and hiding certain members by making them private, This restriction makes it more likely for the user to use the object exactly as intended. Bugs are less likely this way. 37
38 Operator overloading Operators are overloaded functions, and we can overload them ourselves. Most operators (e.g. +, =, &&, <<, new, delete) can be overloaded. Only overload what you need. (Overloading < for class complex makes no sense.) Some operators (e.g.., ::) cannot be overloaded. 38
39 operator+ class complex { public : complex ( double r, double i); complex operator +( complex a); void disp (); ; int main () { complex c1(2.2, 3.3 ), c2(0.8, 1); (c1+c2 ). disp (); // output i complex complex :: operator +( complex a) { return complex ( real +a.real, imag +a. imag ); 39
40 operator+= class complex { public : complex ( double r, double i); complex operator +( complex a); complex operator +=( complex a); ; complex complex :: operator +=( complex a) { return complex ( real +=a.real, imag +=a. imag ); // return * this = * this + a; // return * this = operator +( a); (There are several ways to write operator+=.) 40
41 operator- and operator- There are 2 operator-s: the unary - multiplies by -1 while the binary - subtracts. class complex { public : complex operator -(); // unary - complex operator -( complex a); // binary - ; int main () { complex c1(1.2,0.3 ), c2(0,0); complex c3; c3 = - c1; // unary - called c3 = c1 - c2; // binary - called 41
42 operator- and operatorcomplex complex :: operator -() { return complex (-real,- imag ); complex complex :: operator -( complex a) { return complex (real -a.real,imag -a. imag ); 42
43 operator== class complex { public : bool operator ==( complex a); ; bool complex :: operator ==( complex a) { return ( real ==a. real ) && ( imag ==a. imag ); 43
44 When should you use operator overloads? Only use operator overloads when the meaning is completely clear. Actually classes that benefit from operator overloads are somewhat rare. Nevertheless, you need to know them, because the standard library heavily relies on them. In C++, you learn certain topics not because you ll likely use them but rather because libraries use them. Being good at C++ involves getting comfortable with reading and using libraries. 44
45 namespace The using-directive using namespace std ; means we re using all names within the namespace std. Really, the full name of cout is std::cout. The full name uses the scope resolution operator :: to specify which namespace cout is in. Avoid name conflicts with namespaces. (Just as you would use full names to distinguish an Alice from another Alice.) 45
46 namespace # include <cmath > // using namespace std ; namespace mymath { double sqrt ( double x) { int main () { double d = 9; cout << std :: sqrt (d); // sqrt from cmath cout << mymath :: sqrt ( d); // sqrt from mymath 46
47 using-directive The using-directive using namespace std ; makes all names in std accessible without explicitly referring to its namespace. I.e., it allows you to do string s; instead of std :: string s; 47
48 using-declaration The using-declaration individually specifies the names to be used without referring to their namespaces. # inclue < iostream > # include < string > using std :: cout ; using std :: endl ; using std :: string ; int main () { string s = " Good morning." cout << s << endl ; 48
49 namespace namespaces are helpful in organizing a large code base. (When 100 programmers are working together, naming conflicts will happen.) The using-directive using namespace std ; is bad style. It bypasses the safety namespaces provide, and you may unintentionally use a library feature you didn t know existed. It s safer to individually specify the library features you wish to use with using-declarations. 49
50 #include guards When a codebase gets larger, you often include a single header file multiple times. In hw8, main.cpp contains # include " card.h" # include " deck.h" However, deck.h contains # include " card.h" So card.h is #incuded multiple times in main.cpp. This causes a compile-time error. 50
51 #include guards #include guards remedy this issue. card.h should contain # ifndef CARD_H # define CARD_H # include class card { ; # endif // CARD_H 51
52 #include guards # ifndef CARD_ H // if not defined # define CARD_H # endif // CARD_H 1. The first time card.h is #included, CARD_H is not defined. 2. CARD_H is defined. 3. The header file makes the declarations. 4. #endif matches the #ifndef 5. The second time card.h is #included, CARD_H is defined. So all code until #endif is ignored. 52
53 #pragma once The preprocessor directive #pragma directs the compiler to use certain non-standard features. (So portability can be an issue.) #pragma once tells the compiler to #include the header file only once. I.e., it does the job of #include guard. # pragma once class something { ; #pragma once is easier and less error-prone than #include guards. #pragma once is non-standard, but most compilers (e.g. Clang, GCC(g++), and MS Visual C++) support it. In HW8, you will use #pragma once. In HW9, you will use explicit #include guards. 53
54 Non-member functions Some functions make more sense as non-member functions class complex { ; // Non - member functions complex exp ( complex c) { double r = c. real * cos (c. imag ); double i = c. real * sin (c. imag ); return complex (r,i); Declare and define such functions in the files that declare and define the class, respectively. Header files should be a nice package; if it provides a class, accopany it with useful member and non-member functions. 54
55 Returning references Just as you can get inputs by copy and by reference, you can also return by copy and by reference. Actually, we re not really ready to talk about this topic. (We need to know about copy constructors an destructors.) However, standard library functions do return references when appropriate. So you ll need to at least vaguely understand this topic to read C++ standard library documentation. 55
56 Returning references: example Why does this work? int i = 0; ++++ i; cout << i << endl ; // output 2 This works because the return value of operator++ is int&. int & int :: operator ++() { * this = * this + 1; // increment the int return * this ; // return reference to * this 56
57 Implicitly defined operator= The compiler implicitly defines the copy assignment operator = if you don t provide your own. I.e., the compiler defines T& operator =( RHS T) { // copy all data members of T // into data members of * this return * this ; automatically for class T. 57
58 Implicitly defined operator= Because operator= returns a reference and not a copy, you can do int & int :: operator ++() { return * this = * this + 1; The compound assignment operators +=, -=, *=, etc. also return references. So you can do int & int :: operator ++() { return * this += 1; 58
59 Implicitly defined operator= For our class complex we can do class complex { public : complex operator +( complex a) { return complex ( real + a.real, imag + a. imag ); // complex & operator =( complex a) { // real = a. real ; imag = a. imag ; // return * this ; // complex & operator +=( complex a) { return (* this = * this + a); 59
60 cout and operator<< std::cout is a global variable of class std::ostream. The operator << is overloaded for many classes within the standard library. We can overload it for our custom classes. class complex { ; // Non - member operator overload std :: ostream & operator < <( std :: ostream & s, complex c) { return s << c. real << "+" << c. imag << "i"; using std :: cout ; int main () { complex c1(1.1,2.2 ); cout << c1 <<"\n"; // output i 60
61 cout and operator<< You can do void operator < <( ) { and this will allow cout << c1; However, you need to return the reference to allow chaining cout << c1 << " hello \n"; // same as ( ( cout << c1) << " hello \n" ); (std::endl is a function pointer and we won t talk about it.) 61
62 cout and operator<< If you return a copy and not a reference std :: ostream operator < <( ) { you get a compilation error. (The iostream library prevents you from doing this.) Returning a copied object of class std::ostream wouldn t make sense anyways. What would a copy of std::cout mean? 62
63 Default inputs You can specify default inputs or default arguments in your function declaration. class complex { public : complex ( double r, double i = 0); ; // i = 0 not repeated complex :: complex ( double r, double i) { real = r; imag = i; Don t repeat the specification in the function definition. You can have default arguments in any function. 63
64 Member initializer list In defining constructors, you can use the member initializer list to initialize data members. complex :: complex ( double r, double i) : real (r), imag (i) { The member initializer list is convenient, but sometimes its more than just syntactic sugar. Without the member initializer list, default constructors of members are first called and then the assignment happens. (Sometimes this is wasteful. If there s no default constructor this is infeasible.) With the member initializer list you can choose which constructor to call. 64
65 Struct vs. classes I ve said a struct is a collection of its data members, and a class is collection of its (usually private) data members accompanied by member functions. That is indeed how people view and use structs. But really, there s only one small difference: by default, members of classes are private while members of structs are public. So structs can have private data members and member functions, but then there s no reason to call is a struct. By convention, people expect structs to be just data. It s good style to respect this convention. 65
CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010
CSE 374 Programming Concepts & Tools Hal Perkins Spring 2010 Lecture 19 Introduction ti to C++ C++ C++ is an enormous language: g All of C Classes and objects (kind of like Java, some crucial differences)
More informationCSE 303: Concepts and Tools for Software Development
CSE 303: Concepts and Tools for Software Development Hal Perkins Autumn 2008 Lecture 24 Introduction to C++ CSE303 Autumn 2008, Lecture 24 1 C++ C++ is an enormous language: All of C Classes and objects
More informationPIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics
PIC 10A Pointers, Arrays, and Dynamic Memory Allocation Ernest Ryu UCLA Mathematics Pointers A variable is stored somewhere in memory. The address-of operator & returns the memory address of the variable.
More informationFast Introduction to Object Oriented Programming and C++
Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming
More informationCSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 19 Introduction to C++ C++ C++ is an enormous language: All of C Classes and objects (kind of like Java, some crucial differences) Many
More informationThese are notes for the third lecture; if statements and loops.
These are notes for the third lecture; if statements and loops. 1 Yeah, this is going to be the second slide in a lot of lectures. 2 - Dominant language for desktop application development - Most modern
More informationObject Oriented Design
Object Oriented Design Lecture 3: Introduction to C++ (Continue) Examples using declarations that eliminate the need to repeat the std:: prefix 1 Examples using namespace std; enables a program to use
More informationCpt S 122 Data Structures. Introduction to C++ Part II
Cpt S 122 Data Structures Introduction to C++ Part II Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Objectives Defining class with a member function
More information04-19 Discussion Notes
04-19 Discussion Notes PIC 10B Spring 2018 1 Constructors and Destructors 1.1 Copy Constructor The copy constructor should copy data. However, it s not this simple, and we need to make a distinction here
More informationCh. 12: Operator Overloading
Ch. 12: Operator Overloading Operator overloading is just syntactic sugar, i.e. another way to make a function call: shift_left(42, 3); 42
More informationChapter 2 Basic Elements of C++
C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2-1 Chapter 2 Basic Elements of C++ At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion
More informationChapter 10 Introduction to Classes
C++ for Engineers and Scientists Third Edition Chapter 10 Introduction to Classes CSc 10200! Introduction to Computing Lecture 20-21 Edgardo Molina Fall 2013 City College of New York 2 Objectives In this
More informationC++ Programming: From Problem Analysis to Program Design, Third Edition
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine
More informationPIC 20A The Basics of Java
PIC 20A The Basics of Java Ernest Ryu UCLA Mathematics Last edited: November 1, 2017 Outline Variables Control structures classes Compilation final and static modifiers Arrays Examples: String, Math, and
More informationOperator overloading
1 Introduction 2 The copy constructor 3 Operator Overloading 4 Eg 1: Adding two vectors 5 The -> operator 6 The this pointer 7 Overloading = 8 Unary operators 9 Overloading for the matrix class 10 The
More informationLesson 13 - Vectors Dynamic Data Storage
Lesson 13 - Vectors Dynamic Data Storage Summary In this lesson we introduce the Standard Template Library by demonstrating the use of Vectors to provide dynamic storage of data elements. New Concepts
More informationDistributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes
Distributed Real-Time Control Systems Lecture 17 C++ Programming Intro to C++ Objects and Classes 1 Bibliography Classical References Covers C++ 11 2 What is C++? A computer language with object oriented
More informationCE221 Programming in C++ Part 1 Introduction
CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab
More informationBasic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces
Basic memory model Using functions Writing functions Basics Prototypes Parameters Return types Functions and memory Names and namespaces When a program runs it requires main memory (RAM) space for Program
More informationWelcome 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:
Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams
More informationPIC 10A Flow control. Ernest Ryu UCLA Mathematics
PIC 10A Flow control Ernest Ryu UCLA Mathematics If statement An if statement conditionally executes a block of code. # include < iostream > using namespace std ; int main () { double d1; cin >> d1; if
More informationG52CPP C++ Programming Lecture 13
G52CPP C++ Programming Lecture 13 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last lecture Function pointers Arrays of function pointers Virtual and non-virtual functions vtable and
More informationAnnouncements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy
CSCI 334: Principles of Programming Languages Lecture 18: C/C++ Homework help session will be tomorrow from 7-9pm in Schow 030A instead of on Thursday. Instructor: Dan Barowy HW6 and HW7 solutions We only
More informationAbstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles
Abstract Data Types (ADTs) CS 247: Software Engineering Principles ADT Design An abstract data type (ADT) is a user-defined type that bundles together: the range of values that variables of that type can
More informationOutline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O
Outline EDAF30 Programming in C++ 2. Introduction. More on function calls and types. Sven Gestegård Robertz Computer Science, LTH 2018 1 Function calls and parameter passing 2 Pointers, arrays, and references
More informationLecture 7. Log into Linux New documents posted to course webpage
Lecture 7 Log into Linux New documents posted to course webpage Coding style guideline; part of project grade is following this Homework 4, due on Monday; this is a written assignment Project 1, due next
More informationLecture 10: building large projects, beginning C++, C++ and structs
CIS 330: / / / / (_) / / / / _/_/ / / / / / \/ / /_/ / `/ \/ / / / _/_// / / / / /_ / /_/ / / / / /> < / /_/ / / / / /_/ / / / /_/ / / / / / \ /_/ /_/_/_/ _ \,_/_/ /_/\,_/ \ /_/ \ //_/ /_/ Lecture 10:
More informationIntroduction Of Classes ( OOPS )
Introduction Of Classes ( OOPS ) Classes (I) A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions. An object is an instantiation of a class.
More informationCS 247: Software Engineering Principles. ADT Design
CS 247: Software Engineering Principles ADT Design Readings: Eckel, Vol. 1 Ch. 7 Function Overloading & Default Arguments Ch. 12 Operator Overloading U Waterloo CS247 (Spring 2017) p.1/17 Abstract Data
More informationWeek 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.
Week 2: Console I/O and Operators Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.1) CS 1428 Fall 2014 Jill Seaman 1 2.14 Arithmetic Operators An operator is a symbol that tells the computer to perform specific
More informationVariables. Data Types.
Variables. Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable. We had to write several lines of code, compile them, and then execute the resulting
More informationUnderstanding main() function Input/Output Streams
Understanding main() function Input/Output Streams Structure of a program // my first program in C++ #include int main () { cout
More informationCOMP322 - Introduction to C++ Lecture 01 - Introduction
COMP322 - Introduction to C++ Lecture 01 - Introduction Robert D. Vincent School of Computer Science 6 January 2010 What this course is Crash course in C++ Only 14 lectures Single-credit course What this
More informationWelcome 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:
Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams
More informationADTs & Classes. An introduction
ADTs & Classes An introduction Quick review of OOP Object: combination of: data structures (describe object attributes) functions (describe object behaviors) Class: C++ mechanism used to represent an object
More informationComputing and Statistical Data Analysis Lecture 3
Computing and Statistical Data Analysis Lecture 3 Type casting: static_cast, etc. Basic mathematical functions More i/o: formatting tricks Scope, namspaces Functions 1 Type casting Often we need to interpret
More informationShahram Rahatlou. Computing Methods in Physics. Overloading Operators friend functions static data and methods
Overloading Operators friend functions static data and methods Shahram Rahatlou Computing Methods in Physics http://www.roma1.infn.it/people/rahatlou/cmp/ Anno Accademico 2018/19 Today s Lecture Overloading
More informationCOMP322 - Introduction to C++ Lecture 02 - Basics of C++
COMP322 - Introduction to C++ Lecture 02 - Basics of C++ School of Computer Science 16 January 2012 C++ basics - Arithmetic operators Where possible, C++ will automatically convert among the basic types.
More informationImplementing an ADT with a Class
Implementing an ADT with a Class the header file contains the class definition the source code file normally contains the class s method definitions when using Visual C++ 2012, the source code and the
More informationMakefiles Makefiles should begin with a comment section of the following form and with the following information filled in:
CS 215 Fundamentals of Programming II C++ Programming Style Guideline Most of a programmer's efforts are aimed at the development of correct and efficient programs. But the readability of programs is also
More information04-05 Discussion Notes
04-0 Discussion Notes PIC 10B Spring 018 1 The Build phase 1.1 Declaration vs Definition It is often the case when writing.cpp code that we wish to say a symbol is valid without actually giving the symbol
More informationReference Parameters A reference parameter is an alias for its corresponding argument in the function call. Use the ampersand (&) to indicate that
Reference Parameters There are two ways to pass arguments to functions: pass-by-value and pass-by-reference. pass-by-value A copy of the argument s value is made and passed to the called function. Changes
More informationQUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?
QUIZ on Ch.5 Why is it sometimes not a good idea to place the private part of the interface in a header file? Example projects where we don t want the implementation visible to the client programmer: The
More informationCS3157: Advanced Programming. Outline
CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching
More informationModern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi
Modern C++ for Computer Vision and Image Processing Igor Bogoslavskyi Outline Move semantics Classes Operator overloading Making your class copyable Making your class movable Rule of all or nothing Inheritance
More informationW3101: Programming Languages C++ Ramana Isukapalli
Lecture-6 Operator overloading Namespaces Standard template library vector List Map Set Casting in C++ Operator Overloading Operator overloading On two objects of the same class, can we perform typical
More informationSFU CMPT Topic: Classes
SFU CMPT-212 2008-1 1 Topic: Classes SFU CMPT-212 2008-1 Topic: Classes Ján Maňuch E-mail: jmanuch@sfu.ca Friday 15 th February, 2008 SFU CMPT-212 2008-1 2 Topic: Classes Encapsulation Using global variables
More informationUEE1302 (1102) F10: Introduction to Computers and Programming
Computational Intelligence on Automation Lab @ NCTU Learning Objectives UEE1302 (1102) F10: Introduction to Computers and Programming Programming Lecture 00 Programming by Example Introduction to C++ Origins,
More informationQUIZ Friends class Y;
QUIZ Friends class Y; Is a forward declaration neeed here? QUIZ Friends QUIZ Friends - CONCLUSION Forward (a.k.a. incomplete) declarations are needed only when we declare member functions as friends. They
More informationStarting to Program in C++ (Basics & I/O)
Copyright by Bruce A. Draper. 2017, All Rights Reserved. Starting to Program in C++ (Basics & I/O) On Tuesday of this week, we started learning C++ by example. We gave you both the Complex class code and
More informationFunction Overloading
Function Overloading C++ supports writing more than one function with the same name but different argument lists How does the compiler know which one the programmer is calling? They have different signatures
More informationThe issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management
Session 8 Memory Management The issues Dr Christos Kloukinas City, UoL http://staff.city.ac.uk/c.kloukinas/cpp (slides originally produced by Dr Ross Paterson) Programs manipulate data, which must be stored
More informationProgramming Abstractions
Programming Abstractions C S 1 0 6 B Cynthia Lee Topics du Jour: Make your own classes! Needed for Boggle assignment! We are starting to see a little bit in MarbleBoard assignment as well 2 Classes in
More informationC++ Mini-Course. Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion. C Rulez!
C++ Mini-Course Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion C Rulez! C++ Rulez! C++ Mini-Course Part 1: Mechanics C++ is a
More informationVariables and Constants
HOUR 3 Variables and Constants Programs need a way to store the data they use. Variables and constants offer various ways to work with numbers and other values. In this hour you learn: How to declare and
More informationOutline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor
Outline EDAF50 C++ Programming 4. Classes Sven Gestegård Robertz Computer Science, LTH 2018 1 Classes the pointer this const for objects and members Copying objects friend inline 4. Classes 2/1 User-dened
More informationLecture 18 Tao Wang 1
Lecture 18 Tao Wang 1 Abstract Data Types in C++ (Classes) A procedural program consists of one or more algorithms that have been written in computerreadable language Input and display of program output
More informationAN OVERVIEW OF C++ 1
AN OVERVIEW OF C++ 1 OBJECTIVES Introduction What is object-oriented programming? Two versions of C++ C++ console I/O C++ comments Classes: A first look Some differences between C and C++ Introducing function
More informationCIS 190: C/C++ Programming. Classes in C++
CIS 190: C/C++ Programming Classes in C++ Outline Header Protection Functions in C++ Procedural Programming vs OOP Classes Access Constructors Headers in C++ done same way as in C including user.h files:
More informationC++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay
C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming
More informationEL2310 Scientific Programming
(pronobis@kth.se) Overview Overview Wrap Up Introduction to Object Oriented Paradigm More on and Members Operator Overloading Last time Intro to C++ Differences between C and C++ Intro to OOP Today Object
More informationQUIZ. What is wrong with this code that uses default arguments?
QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code
More informationCS 376b Computer Vision
CS 376b Computer Vision 09 / 25 / 2014 Instructor: Michael Eckmann Today s Topics Questions? / Comments? Enhancing images / masks Cross correlation Convolution C++ Cross-correlation Cross-correlation involves
More informationA brief introduction to C++
A brief introduction to C++ Rupert Nash r.nash@epcc.ed.ac.uk 13 June 2018 1 References Bjarne Stroustrup, Programming: Principles and Practice Using C++ (2nd Ed.). Assumes very little but it s long Bjarne
More informationIII. Classes (Chap. 3)
III. Classes III-1 III. Classes (Chap. 3) As we have seen, C++ data types can be classified as: Fundamental (or simple or scalar): A data object of one of these types is a single object. int, double, char,
More informationy
The Unfit tutorial By Dr Martin Buist Initial version: November 2013 Unfit version: 2 or later This tutorial will show you how to write your own cost function for Unfit using your own model and data. Here
More informationProgramming C++ Lecture 6. Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor
Programming C++ Lecture 6 Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor Jennifer.sartor@elis.ugent.be S Friends 2 Friends of Objects S Classes sometimes need friends. S Friends are defined outside
More informationCOMP322 - Introduction to C++
COMP322 - Introduction to C++ Winter 2011 Lecture 2 - Language Basics Milena Scaccia School of Computer Science McGill University January 11, 2011 Course Web Tools Announcements, Lecture Notes, Assignments
More informationthe gamedesigninitiative at cornell university Lecture 7 C++ Overview
Lecture 7 Lecture 7 So You Think You Know C++ Most of you are experienced Java programmers Both in 2110 and several upper-level courses If you saw C++, was likely in a systems course Java was based on
More informationCSE 333. Lecture 11 - constructor insanity. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington
CSE 333 Lecture 11 - constructor insanity Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington Administrivia Exercises: - New exercise out today, due Monday morning
More informationGE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004
GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004 Functions and Program Structure Today we will be learning about functions. You should already have an idea of their uses. Cout
More informationClasses: A Deeper Look
Classes: A Deeper Look 1 Introduction Implementing a Time Abstract Data Type with a class Class Scope and Accessing Class Members Separating Interface from Implementation Controlling Access to Members
More informationChapter 2. Procedural Programming
Chapter 2 Procedural Programming 2: Preview Basic concepts that are similar in both Java and C++, including: standard data types control structures I/O functions Dynamic memory management, and some basic
More information2 ADT Programming User-defined abstract data types
Preview 2 ADT Programming User-defined abstract data types user-defined data types in C++: classes constructors and destructors const accessor functions, and inline functions special initialization construct
More informationLecture 8. Xiaoguang Wang. February 13th, 2014 STAT 598W. (STAT 598W) Lecture 8 1 / 47
Lecture 8 Xiaoguang Wang STAT 598W February 13th, 2014 (STAT 598W) Lecture 8 1 / 47 Outline 1 Introduction: C++ 2 Containers 3 Classes (STAT 598W) Lecture 8 2 / 47 Outline 1 Introduction: C++ 2 Containers
More informationObject-Oriented Principles and Practice / C++
Object-Oriented Principles and Practice / C++ Alice E. Fischer September 26, 2016 OOPP / C++ Lecture 4... 1/33 Global vs. Class Static Parameters Move Semantics OOPP / C++ Lecture 4... 2/33 Global Functions
More informationProgrammazione. Prof. Marco Bertini
Programmazione Prof. Marco Bertini marco.bertini@unifi.it http://www.micc.unifi.it/bertini/ Hello world : a review Some differences between C and C++ Let s review some differences between C and C++ looking
More informationC++ Support Classes (Data and Variables)
C++ Support Classes (Data and Variables) School of Mathematics 2018 Today s lecture Topics: Computers and Programs; Syntax and Structure of a Program; Data and Variables; Aims: Understand the idea of programming
More informationObject Oriented Design
Object Oriented Design Chapter 9 Initializing a non-static data member in the class definition is a syntax error 1 9.2 Time Class Case Study In Fig. 9.1, the class definition is enclosed in the following
More informationFinancial computing with C++
Financial Computing with C++, Lecture 4 - p1/19 Financial computing with C++ LG Gyurkó University of Oxford Michaelmas Term 2015 Financial Computing with C++, Lecture 4 - p2/19 Outline General properties
More informationComputer Science II Lecture 1 Introduction and Background
Computer Science II Lecture 1 Introduction and Background Discussion of Syllabus Instructor, TAs, office hours Course web site, http://www.cs.rpi.edu/courses/fall04/cs2, will be up soon Course emphasis,
More information4. Structure of a C++ program
4.1 Basic Structure 4. Structure of a C++ program The best way to learn a programming language is by writing programs. Typically, the first program beginners write is a program called "Hello World", which
More informationClasses in C++98 and C++11
Classes in C++98 and C++11 January 10, 2018 Brian A. Malloy Slide 1 of 38 1. When we refer to C++98, we are referring to C++98 and C++03, since they differ only slightly. C++98 contained 3 types of constructors,
More informationObject-oriented Programming in C++
Object-oriented Programming in C++ Working with C and C++ Wolfgang Eckhardt, Tobias Neckel March 23, 2015 Working with C and C++, March 23, 2015 1 Challenges of This Course Heterogeneity of the audience
More informationIntroduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts
Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter
More informationObject-Oriented Programming
- oriented - iuliana@cs.ubbcluj.ro Babes-Bolyai University 2018 1 / 56 Overview - oriented 1 2 -oriented 3 4 5 6 7 8 Static and friend elements 9 Summary 2 / 56 I - oriented was initially created by Bjarne
More informationLECTURE 02 INTRODUCTION TO C++
PowerPoint Slides adapted from *Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* Copyright 2012 Pearson Education Inc. COMPUTER PROGRAMMING LECTURE 02 INTRODUCTION
More informationMARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #1 Examination 12:30 noon, Tuesday, February 14, 2012
MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #1 Examination 12:30 noon, Tuesday, February 14, 2012 Instructor: K. S. Booth Time: 70 minutes (one hour ten minutes)
More informationCS24 Week 3 Lecture 1
CS24 Week 3 Lecture 1 Kyle Dewey Overview Some minor C++ points ADT Review Object-oriented Programming C++ Classes Constructors Destructors More minor Points (if time) Key Minor Points const Motivation
More informationSixth lecture; classes, objects, reference operator.
Sixth lecture; classes, objects, reference operator. 1 Some notes on the administration of the class: From here on out, homework assignments should be a bit shorter, and labs a bit longer. My office hours
More information6.096 Introduction to C++
MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. 6.096 Lecture 3 Notes
More informationObjectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program
Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates
More informationChapter 2: Basic Elements of C++
Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates
More informationC++ Review. CptS 223 Advanced Data Structures. Larry Holder School of Electrical Engineering and Computer Science Washington State University
C++ Review CptS 223 Advanced Data Structures Larry Holder School of Electrical Engineering and Computer Science Washington State University 1 Purpose of Review Review some basic C++ Familiarize us with
More informationCSE 333. Lecture 10 - references, const, classes. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington
CSE 333 Lecture 10 - references, const, classes Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington Administrivia New C++ exercise out today, due Friday morning
More informationChapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction
Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers
More informationTypes, Values, Variables & Assignment. EECS 211 Winter 2018
Types, Values, Variables & Assignment EECS 211 Winter 2018 2 Road map Strings and string I/O Integers and integer I/O Types and objects * Type safety * Not as in object orientation we ll get to that much
More informationCSCI-1200 Data Structures Spring 2018 Lecture 8 Templated Classes & Vector Implementation
CSCI-1200 Data Structures Spring 2018 Lecture 8 Templated Classes & Vector Implementation Review from Lectures 7 Algorithm Analysis, Formal Definition of Order Notation Simple recursion, Visualization
More informationProgramming. Computer. Program. Programming Language. Execute sequence of simple (primitive) instructions What instructions should be provided?
C++ Basics Programming Computer Execute sequence of simple (primitive) instructions What instructions should be provided? Is there a minimum set? (See Turing Machine) Generic Reduce future limitations
More informationAnnotation Annotation or block comments Provide high-level description and documentation of section of code More detail than simple comments
Variables, Data Types, and More Introduction In this lesson will introduce and study C annotation and comments C variables Identifiers C data types First thoughts on good coding style Declarations vs.
More information