Fundamentals of C++ Yingcai Xiao 09/03/08. Outline Class Definition IO Template vector C Pointer Dynamic Memory Allocation.

Slides:



Advertisements
Similar presentations
A C++ Crash Course Part II UW Association for Computing Machinery Questions & Feedback.
Advertisements

C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables.
Rossella Lau Lecture 1, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 1: Introduction What this course is about:
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
Object Oriented Programming C++. ADT vs. Class ADT: a model of data AND its related functions C++ Class: a syntactical & programmatic element for describing.
Streams, Files. 2 Stream Stream is a sequence of bytes Input stream In input operations, the bytes are transferred from a device to the main memory Output.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
VARIABLES, TYPES, INPUT/OUTPUT, ASSIGNMENT OPERATION Shieu-Hong Lin MATH/CS Department Chapel.
Stream Handling Streams - means flow of data to and from program variables. - We declare the variables in our C++ for holding data temporarily in the memory.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
1 Programs Composed of Several Functions Syntax Templates Legal C++ Identifiers Assigning Values to Variables Declaring Named Constants String Concatenation.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 24P. 1Winter Quarter C++ Lecture 24.
1 C++ Syntax and Semantics, and the Program Development Process.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
CIS-165 C++ Programming I CIS-165 C++ Programming I Bergen Community College Prof. Faisal Aljamal.
Week 14 - Monday.  What did we talk about last time?  Introduction to C++  Input and output  Functions  Overloadable  Default parameters  Pass.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Hank Childs, University of Oregon May 13th, 2015 CIS 330: _ _ _ _ ______ _ _____ / / / /___ (_) __ ____ _____ ____/ / / ____/ _/_/ ____/__ __ / / / / __.
Dynamic memory allocation and Pointers Lecture 4.
Monday, Mar 31, 2003Kate Gregory with material from Deitel and Deitel Week 12 Labs 4 and 5 are back File IO Looking ahead to the final.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
1 Original Source : and Problem and Problem Solving.ppt.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
Copyright © 2012 Pearson Education, Inc. Chapter 11: Structured Data.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 16: Introduction to C++
Review 1 List Data Structure List operations List Implementation Array Linked List.
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
CS415 C++ Programming Takamitsu Kawai x4212 G11 CERC building WV Virtual Environments Lab West Virginia University.
1.Which of the following statements is correct?
Lecture – Pointers1 C++ Pointers Joseph Spring/Bob Dickerson School of Computer Science Operating Systems and Computer Networks Based on notes by Bob Dickerson.
1. 2 Review How many bits are in a byte? a) 4 b) 8 c) 16 d) 256.
More About Data Types & Functions. General Program Structure #include statements for I/O, etc. #include's for class headers – function prototype statements.
Programming II Array of objects. this Using the this Pointer this Objects use the this pointer implicitly or explicitly. – this is – this is used implicitly.
1 What is a Named Constant? A named constant is a location in memory that we can refer to by an identifier, and in which a data value that cannot be changed.
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
Lecture 5: Expressions and Interactivity Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
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.
Lecture 01a: C++ review Topics: Setting up projects, main program Memory Diagrams Variables / Types (some of) the many-types-of-const's Input / Output.
CSE 332: C++ template examples Today: Using Class and Function Templates Two examples –Function template for printing different types –Class template for.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 9. Streams & Files.
11 Introduction to Object Oriented Programming (Continued) Cats.
File Processing Files are used for data persistance-permanent retention of large amounts of data. Computer store files on secondary storage devices,such.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Exploring the C++ Stream Library Copyright 2006 Oxford Consulting, Ltd1 February IO Streams  IOStreams are part of the Standard C++ library.
© M. Gross, ETH Zürich, 2014 Informatik I für D-MAVT (FS 2014) Exercise 7 – Pointers.
Classes: Defining Your Own Data Types Basic principles in OOP Define a new data type as a class and use objects of a class Member Functions –Constructors.
CPS120 Introduction to Computer Science Exam Review Lecture 18.
File I/O in C++. Using Input/Output Files A computer file  is stored on a secondary storage device (e.g., disk);  is permanent;  can be used to provide.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
File I/O in C++ I. Using Input/Output Files A computer file is stored on a secondary storage device (e.g., disk); is permanent; can be used to provide.
Computer Science Department Inheritance & Polymorphism.
1 Inheritance and Polymorphism Chapter Getting Started Continue the Cat Management example from previous presentation.
 Virtual Function Concepts: Abstract Classes & Pure Virtual Functions, Virtual Base classes, Friend functions, Static Functions, Assignment & copy initialization,
Lecture 2 Arrays. Topics 1 Arrays hold Multiple Values 2 Accessing Array Elements 3 Inputting and Displaying Array Contents 4 Array Initialization 5 Using.
Introduction to C++ programming Recap- session 1 Structure of C++ program Keywords Operators – Arithmetic – Relational – Logical Data types Classes and.
Pointers A variable that holds an address value is called a pointer variable, or simply a pointer.  What is the data type of pointer variables? It’s not.
C++ Lesson 1.
Java Yingcai Xiao.
Lecture 9 Files, Pointers
CS3340 – OOP and C++ L. Grewe.
C++, OBJECT ORIENTED PROGRAMMING
Programming with Data Files
Chapter 3: Input/Output
File I/O in C++ I.
CHAPTER 4 File Processing.
Using string type variables
File I/O in C++ I.
Presentation transcript:

Fundamentals of C++ Yingcai Xiao 09/03/08

Outline Class Definition IO Template vector C Pointer Dynamic Memory Allocation

class Rectangle { protected: int width; int height; public: Rectangle () { } Rectangle (int cx, int cy) {width = cx; height = cy;} int area() {return with*height;} }; Example: How to define a class (user-defined data type)

Instantiating a Class in C++ Class Name; In C++: “Rectangle rect” declares an object of class Rectangle. int width; int height; Rectangle () Rectangle (int w, int h) Area() rect “rect” is the name of a memory space that stores a Rectangle object.

Console IO  Reading Input: cin  console input  an object of iostreams  only supports one operator >>  reads input for its arguments, one at a time  auto converts input to the type of the arguments  Displaying Output: cout  console output  an object of iostreams  only supports one operator <<  sends output to the console for its arguments, one at a time  auto converts output of the type of the arguments for display  display format can be specified

File IO #include #include // file io streams using namespace std; int main() { string infile, outfile; cout << "Enter input file name: \n"; cin >> infile; cout << "Enter output file name: \n"; cin >> outfile; ifstream in(infile.data()); // Open for reading ofstream out(outfile.data()); // Open for writing string s; while(getline(in, s)) // Discards newline char out << s << "\n"; //... must add it back } ///:~

Template (Type Variables) x; Where type, T, is a variable too. T : int => int x; T : float => float x;

vector (smart array) To use: #include To define: vector v; To add an element: v.push_back(object); To access an element: v[i] (just like an array) Eaxmples: vector vi; vector vs; int i; string s; cin >> i >> s; vi.push_back(i); vs.push_back(s); cout << vi[0] << vs[0];

C in C++ Data storage types: int, float, char, array (e.g., int ia[4];), enum, struct, union No classes in C. Computation operators: Math: +, -, *, /, %, =, -=, +=, *=, /= Logical:, -, ==, !=, ||, &&, bitwise: |, &, >>, <<,^ Control statements: if-else, while, do-while, for, switch,

Pointers in C and C++

Variables in C and C++ Variable A variable is a named memory space. The memory space stores the value of the variable. The size of the memory is determined by the variable’s type. The limit of the variable is determined by the size of the memory and the type of the variable. Example: int i = 8;i (4 bytes of memory) 8 The memory of a variable is allocated at compile time. The memory of an automatic variable is automatically freed at run time when the variable is no longer in used. By default all variables are automatic. The following statements are the same: int i = 8; auto int i = 8;

Arrays in C and C++ An array of memory can be allocated as int ia[2]; ia[0] = 1; ia[1] = 2; or int ia[2] = {1,2}; or int ia[] = {1,2}; Example: int ia[2] = {1,2}; ia[0] ia[1] (4 bytes each) 1 2 Array memories are “allocated” at compile time.

Address of a Variables & Operator & returns the address of an variable e.g.: &i, &ia[0], &ia[1] The address of a memory is expressed as a hex number e.g.: 0xffaabbcc

Pointers in C and C++ int i = 8; ip = &i; i Pointer A pointer is a named memory space. The size of the memory is determined by the OS (32 bits, 64 bits, …), and it determines the maximum addressing space of the OS. The memory space of a pointer stores the address of another memory space. We usually say, the pointer points to the memory space. The size of the pointed memory space is determined by the type of the pointer. A pointer is declared as type * name; 8 0xffaabbcc Example: int * ip; ip (4 bytes of memory for a 32bit OS)

Dynamical Memory Allocation (DMA) ip = new (int); no name Memories can be allocated at run-time (dynamic memory allocation). “new” is the operator for DMA. It allocates a memory and returns its address (but gives it no name.) A pointer is needed to store the address of a dynamically allocated memory. The size of the memory is determined by the argument supplied to “new”. Operator “*” dereference a pointer to access the memory it points to. A pointer needs to point to a valid memory before being dereferenced. A dereferenced pointer can be used just like a named memory (a regular variable). 0xffaabbcc int * ip; ip (4 bytes of memory for 32bit OS) *ip = 8; cout << *ip; 8

Dereferencing a DMA object There are two ways to dereference a DMA object. * -> Example: Dog *dp; dp = new Dog(“Stommy”); cout << (*dp).getName(); cout getName(); Exam Pet.cpp

Your second C++ Program /* Pet.cpp. This program demonstrates OOP constructs in C++ Dr. Xiao (9/6/07), adopted from TIC++. */ #include // head file for predefined io classes and objects #include // head file for the predefined string class #include // head file for the predefined vector template using namespace std; class Pet { // define a class, group everything together, encapsulate as needed. protected: string name; // protected members can be accessed by child classes public: Pet() {name = “I have no name.";} // default constructor Pet(string nm){name = nm;} // constructor string getName() {return name;} // to be inherited by child classes //virtual method, to be overridden by child classes, for polymorphism virtual string speak() const { return “’I can't speak.’”; } };

Your second C++ Program class Dog : public Pet { // inheritance public: Dog(){name = “I am a dog without a name.";} Dog(string nm){name = nm;} string speak() const { return "'bark! bark!'"; } }; class Cat : public Pet { public: Cat(){name = " I am a cat without a name. ";} Cat(string nm){name = nm;} string speak() const { return "'meow! meow!'"; } };

Your second C++ Program int main() { Dog d("Midnight"); Cat c("Ginger"); Pet p("Dummy"); cout << d.getName() << " says, " << d.speak() <<endl; cout << c.getName() << " says, " << c.speak() <<endl; cout << p.getName() << " says, " << p.speak() <<endl; cout << “We put all the pets together to make it easier to take care of them (code reuse). \n”; vector pets; // “vector” mimics variable-size array, its type is a variable too (template) pets.push_back(d); pets.push_back(c); pets.push_back(p); for(int i=0; i<pets.size();i++) cout << "Pet " << i << " (" << pets[i].getName()<< ") " << " says " << pets[i].speak() << endl; cout << "The above did not work correctly. No one can speak now. \n”; cout << “Incorrect use of virtual methods for polymorphism. \n";

Your second C++ Program cout << "The following do work correctly. \n”; cout << “Correct use of a virtual method for polymorphism. \n"; vector pets2; // pointer type pets2.push_back(&d); // taking address of d pets2.push_back(&c); pets2.push_back(&p); for(int i=0; i<pets2.size();i++) cout getName()<< ") " speak() << endl; cout << “Correct use of a virtual method for polymorphism. \n"; vector pets3; pets3.push_back(new Dog("Midnight2")); // a new dog created at run time pets3.push_back(new Cat("Ginger2")); pets3.push_back(new Pet("Dummy2")); for(int i=0; i<pets3.size();i++) cout getName()<< ") " speak() << endl; cout > a; }