ACM C++ Tutorial Nathan Ratliff. Development Environments Windows – Microsoft Visual C++ Note: It’s not ansi standard Linux / Unix – GCC / G++

Slides:



Advertisements
Similar presentations
Chapter 18 Vectors and Arrays
Advertisements

Various languages….  Could affect performance  Could affect reliability  Could affect language choice.
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,
Informática II Prof. Dr. Gustavo Patiño MJ
Chapter 15 Memory Management: Four main memory areas for a C++ program: Code: code for instructions, methods, etc. static data: Global variables (declared.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
1 Day 03 Introduction to C. 2 Memory layout and addresses r s int x = 5, y = 10; float f = 12.5, g = 9.8; char c = ‘r’, d = ‘s’;
CSE 2501 Review Declaring a variable allocates space for the type of datum it is to store int x; // allocates space for an int int *px; // allocates space.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
 2006 Pearson Education, Inc. All rights reserved Midterm review Introduction to Classes and Objects.
Pointers. Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location.
1 ES 314 Advanced Programming Lec 3 Sept 8 Goals: complete discussion of pointers discuss 1-d array examples Selection sorting Insertion sorting 2-d arrays.
C and Data Structures Baojian Hua
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Memory Layout C and Data Structures Baojian Hua
CS-2303 System Programming Concepts
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
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.
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
Introduction to C++. Overview C++? What are references Object orientation Classes Access specifiers Constructor/destructor Interface-implementation separation.
Pointer Data Type and Pointer Variables
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Recap, Test 1 prep, Composition and Inheritance. Dates Test 1 – 12 th of March Assignment 1 – 20 th of March.
By – Tanvir Alam.  This tutorial offers several things.  You’ll see some neat features of the language.  You’ll learn the right things to google. 
 200 Total Points ◦ 74 Points Writing Programs ◦ 60 Points Tracing Algorithms and determining results ◦ 36 Points Short Answer ◦ 30 Points Multiple Choice.
Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location. This is.
February 11, 2005 More Pointers Dynamic Memory Allocation.
This set of notes is adapted from that provided by “Computer Science – A Structured Programming Approach Using C++”, B.A. Forouzan & R.F. Gilberg, Thomson.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 5 An Array Class Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review Part-I.
C++ Memory Overview 4 major memory segments Key differences from Java
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 4 Pointers and Dynamic Arrays Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
 Managing the heap  Resource acquisition is initialization (RAII)  Overriding operator new and delete  Class-based memory pools.
Dynamic Memory Allocation. Domain A subset of the total domain name space. A domain represents a level of the hierarchy in the Domain Name Space, and.
Dynamic memory allocation and Pointers Lecture 4.
Current Assignments Start Reading Chapter 6 Project 3 – Due Thursday, July 24 Contact List Program Homework 6 – Due Sunday, July 20 First part easy true/false.
Concordia TAV 2002 Comp5421_421 Comp5421 Object Oriented Programming Using C++ Efficiently Lecture 4 (2) Tianxiang Shen Summer 2002 Department of Computer.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Pointers and Dynamic Arrays
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
 140 Total Points ◦ 100 Points Writing Programs ◦ 24 Points Tracing Algorithms and determining results ◦ 16 Points Short Answer  Similar to quizzes.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 16: Introduction to C++
 200 Total Points ◦ 75 Points Writing Programs ◦ 60 Points Tracing Algorithms and determining results ◦ 35 Points Short Answer ◦ 30 Points Multiple Choice.
CS415 C++ Programming Takamitsu Kawai x4212 G11 CERC building WV Virtual Environments Lab West Virginia University.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Preprocessor Midterm Review Lecture 7 Feb 17, 2004.
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.
11 Introduction to Object Oriented Programming (Continued) Cats.
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.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
PROGRAMMING 1 – HELPER INSTRUCTIONS ACKNOWLEDGEMENT: THE SLIDES ARE PREPARED FROM SLIDES PROVIDED BY NANCY M. AMATO AND JORY DENNY 1.
CSE 303 Concepts and Tools for Software Development Richard C. Davis UW CSE – 10/11/2006 Lecture 7 – Introduction to C.
Lecture 01d: C++ review Topics: functions scope / lifetime preprocessor directives header files C structures ("simple classes")
LECTURE 3 Translation. PROCESS MEMORY There are four general areas of memory in a process. The text area contains the instructions for the application.
Lecture 3 Translation.
Object Lifetime and Pointers
Eugene Hsu.
Pointers Revisited What is variable address, name, value?
Dynamically Allocated Memory
understanding memory usage by a c++ program
Chapter 15 Pointers, Dynamic Data, and Reference Types
Brought to you by C++ Tutorial Brought to you by
Chapter 15 Pointers, Dynamic Data, and Reference Types
Created by Hwansoo Han Edited by Ikjun Yeom
Dynamic Memory.
Pointers, Dynamic Data, and Reference Types
Presentation transcript:

ACM C++ Tutorial Nathan Ratliff

Development Environments Windows – Microsoft Visual C++ Note: It’s not ansi standard Linux / Unix – GCC / G++

Hello World #include // For cout using namespace std; int main(){ cout << “Hello World!” << endl; return 0; }

Compilation Model Preprocessor – Resolves all preprocessor directives – #include, #define macros, #ifdef, etc. Compiler – Converts text into object files – May have unresolved interobject references Linker – Resolves all interobject references (or gives you a linker error) – Creates the binary executable Loader – Loads the program into RAM and runs the main() function

Compiling with g++ tahiti:~$ ls source_file1.ccsource_file2.cc tahiti:~$ g++ -c source_file1.cc tahiti:~$ g++ -c source_file2.cc tahiti:~$ ls source_file1.ccsource_file1.osource_file2.cc source_file2.o tahiti:~$ g++ -o exe_prog source_file1.o source_file2.o tahiti:~$ ls exe_prog source_file1.ccsource_file1.o source_file2.ccsource_file2.o tahiti:~$./exe_prog Hello world!

Simple makefile source_file1.o: source_file1.cc g++ -c source_file1.cc source_file2.o: source_file2.cc g++ -c source_file2.cc exe_prog: source_file1.o source_file2.o g++ -o exe_prog source_file1.o source_file2.o

A Cooler Makefile CXX = g++ CXXFLAGS = -Wall -ansi -g all : exe_prog source_file1.o : source_file1.cc source_file1.h $(CXX) $(CXXFLAGS) -c $< source_file2.o : source_file2.cc source_file2.h $(CXX) $(CXXFLAGS) -c $< exe_prog : source_file1.o source_file2.o $(CXX) -o $^ clean : rm –f core *.o *~

Preprocessor Directives Performed before compilation – Compiler errors show up in wierd places for confusing reasons #include or #include “filename” – Copies and pastes filename into the current file #define LABEL [value] – Substitutes value for LABEL everywhere LABEL is used in the body of the code IMPORTANT: preprocessor directives are never followed by semicolons! #define can also be used without specifying a value – #define LABEL We can check for existance such as in #ifdef COW #ifndef COW_SIZE #define COW_SIZE 12 #endif int intAry[COW_SIZE]; #else #ifndef ANIMAL_SIZE #define ANIMAL_SIZE 1 #endif int intAry[ANIMAL_SIZE]; #endif Labels don’t have to be captalized...but everyone’s doing it

#define macros #define can be used to create macros with parameters Used mostly in C because C++ has templates Take a look at #define TAX(x) x * 0.05 int main(){ int sales = 20; // I’m okay :) int tax = TAX(sales); // I’m evil! :( Why? tax = TAX(sales + 10); return 0; } // Better definition #define SAFE_TAX(x) (x) * 0.05

Class Syntax class MyClass{ public: int getNum(){return m_num;} void setNum(int num){m_num = num} private: int m_num; }; // Don’t forget this semicolon! Note: C++ also offers a struct aggregated data type, which is very similar to a class

Separating Class Definition from Implementation MyClass.h: #ifndef MY_CLASS_H #define MY_CLASS_H class MyClass{ public: int getNum(); void setNum(int num); private: int m_num; }; #endif // MY_CLASS_H MyClass.cc: #include “MyClass.h” int MyClass::getNum(){ return m_num; } void MyClass::setNum(int num){ m_num = num; }

Procedural Programming Writing free floating functions or procedures that are disassociated from all classes C is completely procedural, but C++ mixes both object oriented and procedural programming #include using namespace std; int func1(int i){...} int func2(int i){...} int func3(int i){...} int func4(int i){...} int func5(int i){...} int func6(int i){...} int main(){ int k = func1(func2(func3(func4))); cout << func5(func6(k)) << endl; return 0; }

Memory Management Pointers Memory allocation and deallocation – new and delete – malloc() and free() (Used mainly in C) – Don’t mix them! Problems and pitfalls – Dangling pointers – Memory leaks Class destructors

Pointers Variables that contain memory addresses The myriad uses of * – Declaring pointer int *i; – Dereferencing j = *i; – Multiplying i = j*k; The address of operator & – Gets you the address of a variable – int *i = &j; The pointer i now contains the address of int variable j

A Pointer Example int main(){ int i, j; int *pi, *pj; i = 5; j = i; pi = &i; pj = pi; *pj = 4; cout << i << “ “; cout << j << “ “; cout << *pi << “ “; cout << *pj << endl; return 0; } > 4, 5, 4, 4

Memory allocation Stack vs. heap – Stack grows down – Heap grows up Static Memory – Size fixed during compilation – Has scope – Allocated on stack Dynamic Memory – Variable size – created at run time – Allocated on heap using new – Alive until deallocated using delete... 0xFF Stack Heap 0xFD 0xFC 0x03 0x02 0x01 0x00 0xFE

Memory Allocation Examples new returns a pointer to the dynamically created object. #include “Cow.h” #include using namespace std; int main(){ int *i = new int(12); Cow *c = new Cow;... delete i; delete c; return 0; }

Problems Dangling pointers – Pointers to memory that has already been deallocated – segmentation fault (core dump)... or worse.... Memory leak – Loosing pointers to dynamically allocated memory – Substantial problem in many commercial products See Windows 98 – C++ HAS NO GARBAGE COLLECTION!

Dangling pointer examples int main(){ int *myNum = new int(12); int *myOtherNum = myNum; delete myNum; cout << *myOtherNum << endl; return 0; } int* badFunction(){ int num = 10; return &num; } int* stillBad(int n){ n += 12; return &n; } int main(){ int num = 12; int *myNum = badFunction(); int *myOtherNum = stillBad(num); cout << *myNum << “, “; cout << *myOtherNum << endl; return 0; }

Memory Leak Examples int main(){ int *myNum = new int(12); myNum = new int(10); // Oops... delete myNum; return 0; } int evilFunction(){ int *i = new int(9); return *i; } int main(){ int num = evilFunction(); // I’m loosing my memory!! return 0; }

Class Destructors If a class dynamically allocates memory, we need a way to deallocate it when it’s destroyed. Distructors called upon distruction of an object class MyClass{ public: MyClass(){ // Constructor } ~MyClass(){ // Destructor }... };

Copy Constructor and Assignment Operator Copy Constructor: class Rooster{ public:... Rooster(const Rooster &rhs){ // Do your deep copy }... };... // Usage Rooster r(12); Rooster s(r); Assignment Operator: class Rooster{ public:... Rooster& operator=(const Rooster &rhs){ // Copy stuff }... };... // Usage Rooster r(12), s(10); r = s;

Canonical Form All classes should have each of the following: – Default constructor – Copy constructor – Assignment operator – Destructor // Canonical Cow class Cow{ public: Cow(){...} Cow(const Cow &rhs){...} Cow& operator=(const Cow &c) {...} ~Cow(){...}... };

C++ Arrays #define ARRAY_LENGTH 5 int main(){ int ary[ARRAY_LENGTH]; for (int i = 0; i < ARRAY_LENGTH; i++){ ary[i] = i; } int *ary2 = ary + ARRAY_LENGTH/2; // Huh?!? for (int i = 0; i < ARRAY_LENGTH; i++){ cout << ary[i] << “ “; } cout << endl; for (int i = -ARRAY_LENGTH/2; i < ARRAY_LENGTH/2;i++){ cout << ary2[i] << “ “; // Huh, again... } cout << endl; return 0; } Output: >

Arrays Explained The name is a label for the address of the first element – Array ary[i] gives you the value stored in the i th memory location after ary (in int sized increments) – BUT IT IS NOT A POINTER! There is no memory allocated to store the address of the first element Be careful! Interchanging pointers with arrays can get really confusing if you don’t understand this. The length of a statically allocated array must be known during compilation, i.e. it must be a constant If it’s not known during compilation, we should use dynamically allocated arrays

Dynamically Allocated Arrays Used when the array length is not known during compilation Example: int size; cin >> size; int ary[] = new int[size]; for (int i = 0; i < size; i++){ ary[i] = i; } delete [] ary; Note that the delete operator must be prepended with [] when used on dynamically allocated arrays

References Lippman, Stanley B. C++ Primer, Third Edition. Addison-Wesely, 1998 Parlante, Nick. Pointers and Memory, copyright Shtern, Victor. Core C++: A Software Engineering Approach. Prentice Hall PTR, 1998 Stroustrup, Bjarne. The C++ Programming Language. Addison-Wesley, 1997 ACM Tutorials: ACM library in Sieg 326