Programming Languages and Paradigms C++. C++ program structure  C++ Program: collection of files Header files CPP source files  Files contain class,

Slides:



Advertisements
Similar presentations
Chapter 18 Vectors and Arrays
Advertisements

Lesson 13 Introduction to Classes CS1 Lesson Introduction to Classes1.
Data Structures Using C++1 Chapter 3 Pointers and Array-Based Lists.
Introduction to Programming Lecture 39. Copy Constructor.
F UNCTION O VERLOADING Chapter 5 Department of CSE, BUET 1.
Review of Stacks and Queues Dr. Yingwu Zhu. Our Focus Only link-list based implementation of Stack class Won’t talk about different implementations of.
Object Oriented Programming COP3330 / CGS5409.  C++ Automatics ◦ Copy constructor () ◦ Assignment operator =  Shallow copy vs. Deep copy  DMA Review.
Chapter 7: User-Defined Functions II
Pointers Revisited l What is variable address, name, value? l What is a pointer? l How is a pointer declared? l What is address-of (reference) and dereference.
Lecture 3 Feb 4 summary of last week’s topics and review questions (handout) Today’s goals: Chapter 1 overview (sections 1.4 to 1.6) c++ classes constructors,
Chapter 15 Memory Management: Four main memory areas for a C++ program: Code: code for instructions, methods, etc. static data: Global variables (declared.
Object Oriented Programming.  OOP Basic Principles  C++ Classes  September 2004  John Edgar 22.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
Review of C++ Programming Part II Sheng-Fang Huang.
OOP Languages: Java vs C++
Programming Languages and Paradigms Object-Oriented Programming.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
Pointer Data Type and Pointer Variables
Programming Languages and Paradigms Object-Oriented Programming (Part II)
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
Programming Languages and Paradigms Programming C++ Classes.
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+
CMSC 202 Lesson 14 Copy and Assignment. Warmup Write the constructor for the following class: class CellPhone { public: CellPhone(int number, const string&
Data Structures Using C++1 Chapter 3 Pointers and Array-Based Lists.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
The Big Three Based on Weiss “Data Structures and algorithm Analysis CS240 Computer Science II.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
Review of Stacks and Queues Dr. Yingwu Zhu. How does a Stack Work? Last-in-First-out (LIFO) data structure Adding an item Push operation Removing an item.
Object-Based Programming Mostly Review. Objects Review what is object? class? member variables? member functions? public members? private members? friend.
CMSC 202, Version 3/02 1 Copy Constructors and Overloaded Assignment.
Data Structures Using C++1 Chapter 3 Pointers Dr. Liu.
OOP in C++ CS 124. Program Structure C++ Program: collection of files Source (.cpp) files be compiled separately to be linked into an executable Files.
Data Structures Using C++1 Chapter 3 Pointers and Array-Based Lists.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
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.
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.
Dynamic Memory Review l what is static, automatic, dynamic variables? Why are dynamic(ally allocated) variables needed l what is program stack? Function.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review 2.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
1 // SPECIFICATION FILE (dynarray.h) // Safe integer array class allows run-time specification // of size, prevents indexes from going out of bounds, //
17-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
Pointer to an Object Can define a pointer to an object:
Procedural and Object-Oriented Programming
Pointers and Dynamic Arrays
Andy Wang Object Oriented Programming in C++ COP 3330
C++ Object-Oriented Programming
Introduction to Classes
Class: Special Topics Copy Constructors Static members Friends this
Memberwise Assignment / Initialization
Dynamic Memory Review what is static, automatic, dynamic variables? why are dynamic(ally allocated) variables needed what is program stack? function.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Introduction to Classes
understanding memory usage by a c++ program
Chapter 15 Pointers, Dynamic Data, and Reference Types
Chapter 15 Pointers, Dynamic Data, and Reference Types
Recitation Course 0603 Speaker: Liu Yu-Jiun.
CS410 – Software Engineering Lecture #5: C++ Basics III
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
SPL – PS3 C++ Classes.
Presentation transcript:

Programming Languages and Paradigms C++

C++ program structure  C++ Program: collection of files Header files CPP source files  Files contain class, function, and global variable declarations/definitions  main() function serves as an entry point (just like in C)

Header Files (.h)  Contains class declarations  Prototypes for functions outside of classes  Others

Source Files (.cpp)  Function/method definitions  Directives (e.g., #include, #define)  Variables and initialization (global/static variables)

Variables in C++  Regular variables int x; x = 5; bankaccount b;  Pointers int *p; p = & x; bankaccount *q; q = new bankaccount(); … delete q;  References/Aliases int & r = x; // initialization required  Arrays int num[20]; int *a; a = new int[size]; bankaccount *accts; accts = new bankaccount[10]; … delete[] accts;

Class declaration  class c { private: members … public: members … };  Members (fields and methods) grouped into public, private or protected regions  Fields can be regular variables, arrays, pointers, or references  Method declarations are (often) prototypes Method defined separately from the class declaration

Example: class declaration class car { private: int dist; double gas; public: car(); void drive( int km ); void loadGas( double lit ); int getOdometerReading(); double getGasLeft(); };

Example: class declaration class car { private: int dist; double gas; public: car(); void drive( int km ); void loadGas( double lit ); int getOdometerReading(); double getGasLeft(); }; fields constructor methods

Example: method definitions car::car() { dist = 0; gas = 40.0; } void car::drive( int km ) { dist += km; gas -= km/10.0; } void car::loadGas( double lit ) { gas += lit; } int car::getOdometerReading() { return dist; } double car::getGasLeft() { return gas; }

Example: using objects int main() { car c; c.drive( 20 ); c.loadGas( 2 ); cout << "c: km-" << c.getOdometerReading() << " liters-" << c.getGasLeft() << endl; return 0; }

Role and necessity of header files  For a source file to compile correctly, the appropriate declarations need to precede the use of a class or function Differentiate declaration from definition  Both the source file containing class definitions and the source file using the class must include the header file

Exercise: defining a C++ class Assemble the following C++ project: banktester.cpp: using the bankaccount class and the power function power.h: contains prototype for the power function power.cpp: code for the power function bankaccount.h: header file for the bankaccount class (needs to be revised) bankaccount.cpp: source file for the bankaccount class (needs to be created)  Compare your output with correct output

C++ objects and copies bankaccount a(100); bankaccount b; bankaccount c = a; b = a;

C++ objects and copies bankaccount a(100); bankaccount b; bankaccount c = a; b = a; 100 balance a

C++ objects and copies bankaccount a(100); bankaccount b; bankaccount c = a; b = a; 100 balance a 0 b

C++ objects and copies bankaccount a(100); bankaccount b; bankaccount c = a; b = a; 100 balance a 0 b 100 balance c

C++ objects and copies bankaccount a(100); bankaccount b; bankaccount c = a; b = a; 100 balance a 100 balance b 100 balance c

Pointers as fields  Suppose a class has fields that are pointers Often because of dynamically allocated data  Introduces complexity when copying objects  In C++, the default is a shallow copy Field values are copied verbatim If fields are pointers, this is often not the desired intention  A deep copy requires additional coding

Example: integer vector class intvector { private: int size; int * data; public: intvector(); intvector(int s); // other methods... };

Example: integer vector intvector::intvector() { size = 5; data = new int[5]; } intvector::intvector(int s) { size = s; data = new int[s]; }

C++ objects and copies (pointers) intvector a; intvector b(10); intvector c = a; b = a;

C++ objects and copies (pointers) intvector a; intvector b(10); intvector c = a; b = a; data a 5 size

C++ objects and copies (pointers) intvector a; intvector b(10); intvector c = a; b = a; data a 5 sizedata b 10 size

C++ objects and copies (pointers) intvector a; intvector b(10); intvector c = a; b = a; data a 5 sizedata b 10 sizedata c 5 size

C++ objects and copies (pointers) intvector a; intvector b(10); intvector c = a; b = a; data a 5 sizedata b 5 sizedata c 5 size

The intention intvector a; intvector b(10); intvector c = a; b = a; data a 5 sizedata b 10 sizedata c 5 size 5

Variables going out of scope void method() { int i = 10; bankaccount b; intvector v; //... } int main() { // before method(); // after return 0; } data v 5 size 0 balance b 0 i

Variables going out of scope void method() { int i = 10; bankaccount b; intvector v; //... } int main() { // before method(); // after return 0; } data v 5 size 0 balance b 0 i ? Memory leak!

What needs to be programmed  Destructor De-allocates previously allocated memory (need to call delete on pointers) Signature: ~classname()  Copy constructor Creates an object given an existing object Need to allocate (construct) and then copy Signature: classname( const classname& c )  Assignment operator Copies data from an existing object into an existing object Need to de-allocate, allocate, then copy Signature: classname& operator=( const classname& c )

intvector destructor intvector::~intvector() { delete [] data; } De-allocates memory allocated by data = new int[size];

intvector copy constructor intvector::intvector(const intvector& c) { size = c.size; data = new int[size]; for(int i = 0; i < size; i++) data[i] = c.data[i]; } allocate then, copy

intvector assignment intvector& intvector::operator=(const intvector& c) { // TODO: to guard against self-assignment delete [] data; size = c.size; data = new int[size]; for(int i = 0; i < size; i++) data[i] = c.data[i]; return *this; } De-allocate existing data finally, copy then, re-allocate

Points to ponder  When is a copy constructor called? someclass a = b; someclass c(a); When passing an object parameter during method calls: somemethod(a);  Why do we need to guard against self- assignment? What happens to this statement?: x = x; Will a programmer ever perform self- assigmment? ( maybe: a[i] = a[j]; )

Lab  Write a dataset class with the following methods: void addscore(double score): adds a score to the dataset double computemean(): returns the average of the scores added so far (assume mean=0 if there are no scores in the dataset) double computestdev(): returns the standard deviation: the squareroot of the average of squares of the difference of each element from the mean  A tester program (dstester.cpp) is provided  The dataset class should be dynamic Make the array of scores “grow” in size as necessary

Lab, continued  Rules on dataset capacity Begin with a capacity of size 10 Whenever addscore is called on a full dataset, double the capacity  Make sure to implement a destructor, copy constructor and assignment operator tester2() function tests whether you have programmed this correctly