C++ Tutorial Rob Jagnow

Slides:



Advertisements
Similar presentations
1 C++Tutorial Rob Jagnow This tutorial will be best for students who have at least had some exposure to Java or another comparable programming language.
Advertisements

ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 10: Appendices.
Inheritance, Polymorphism, and Virtual Functions
CS-2303 System Programming Concepts
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++ Tutorial Rob Jagnow. Overview Pointers Arrays and strings Parameter passing Class basics Constructors & destructors Class Hierarchy Virtual Functions.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointer Data Type and Pointer Variables
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Recap, Test 1 prep, Composition and Inheritance. Dates Test 1 – 12 th of March Assignment 1 – 20 th of March.
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.
C++ language first designed or implemented In 1980 by Bjarne Stroustrup, from Bell labs. that would receive formally this name at the end of 1983.
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+
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Lecture 3: Getting Started & Input / Output (I/O) “TRON” Copyright 1982 (Walt Disney Productions)
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
Programming Fundamentals1 Chapter 8 OBJECT MANIPULATION - INHERITANCE.
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.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
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.
Java & C++ Comparisons How important are classes and objects?? What mechanisms exist for input and output?? Are references and pointers the same thing??
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
C++ Namespaces, Exceptions CSci 588: Data Structures, Algorithms and Software Design All material not from online sources copyright © Travis Desell, 2011.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
1 Ugly Realities The Dark Side of C++ Chapter 12.
Data Structures Lecture 4: Classes in C++ Azhar Maqsood NUST Institute of Information Technology (NIIT)
Design issues for Object-Oriented Languages
Lecture 3: Getting Started & Input / Output (I/O)
Hank Childs, University of Oregon
Pointer to an Object Can define a pointer to an object:
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Procedural and Object-Oriented Programming
Pointers and Dynamic Arrays
Function: Declaration
CS 215 Final Review Ismail abumuhfouz Fall 2014.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Andy Wang Object Oriented Programming in C++ COP 3330
Command Line Arguments
Introduction to Classes
Exceptions An exception signals an error, and has the ability to propagate upward through the call stack for easier management To “raise” an exception,
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Introduction to Classes
Chapter 15 Pointers, Dynamic Data, and Reference Types
Java Programming Language
Pointers, Dynamic Data, and Reference Types
Inheritance, Polymorphism, and Virtual Functions
Chapter 15 Pointers, Dynamic Data, and Reference Types
CISC/CMPE320 - Prof. McLeod
CISC/CMPE320 - Prof. McLeod
7 Arrays.
9-10 Classes: A Deeper Look.
Part 1- C++ Class Features
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Functions Reasons Concepts Passing arguments to a function
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
Lecture 8 Object Oriented Programming (OOP)
More C++ Classes Systems Programming.
9-10 Classes: A Deeper Look.
Presentation transcript:

C++ Tutorial Rob Jagnow This tutorial will be best for students who have at least had some exposure to Java or another comparable programming language. Rob Jagnow

Overview Pointers Arrays and strings Parameter passing Class basics Constructors & destructors Class Hierarchy Virtual Functions Coding tips Advanced topics Advanced topics: friends, protected, inline functions, const, static, virtual inheritance, pure virtual function (e.g. Intersect(ray, hit) = 0), class hierarchy.

Pointers Create a pointer Allocate memory Set value at given address int *intPtr; intPtr = new int; *intPtr = 6837; delete intPtr; int otherVal = 5; intPtr = &otherVal; Allocate memory Set value at given address *intPtr 6837 intPtr 0x0050 Deallocate memory Change intPtr to point to a new location *intPtr 5 otherVal intPtr 0x0054 &otherVal

Arrays Stack allocation Heap allocation int intArray[10]; intArray = new int[10]; intArray[0] = 6837; ... delete[] intArray; C++ arrays are zero-indexed.

Strings A string in C++ is an array of characters char myString[20]; strcpy(myString, "Hello World"); Strings are terminated with the NULL or '\0' character myString[0] = 'H'; myString[1] = 'i'; myString[2] = '\0'; printf("%s", myString); output: Hi

Parameter Passing pass by value Make a local copy of a and b int add(int a, int b) { return a+b; } int a, b, sum; sum = add(a, b); pass by reference Pass pointers that reference a and b. Changes made to a or b will be reflected outside the add routine int add(int *a, int *b) { return *a + *b; } int a, b, sum; sum = add(&a, &b);

Parameter Passing pass by reference – alternate notation int add(int &a, int &b) { return a+b; } int a, b, sum; sum = add(a, b);

Class Basics Prevents multiple references Include a library file #ifndef _IMAGE_H_ #define _IMAGE_H_ #include <assert.h> #include "vectors.h“ class Image { public: ... private: }; #endif Prevents multiple references Include a library file Include a local file Variables and functions accessible from anywhere Note that “private:” is the default Variables and functions accessible only from within this class’s functions

Creating an instance Stack allocation Heap allocation Image myImage; myImage.SetAllPixels(ClearColor); Heap allocation Image *imagePtr; imagePtr = new Image(); imagePtr->SetAllPixels(ClearColor); ... delete imagePtr; Stack allocation: Constructor and destructor called automatically when the function is entered and exited. Heap allocation: Constructor and destructor must be called explicitly.

Organizational Strategy image.h Header file: Class definition & function prototypes void SetAllPixels(const Vec3f &color); image.C .C file: Full function definitions void Image::SetAllPixels(const Vec3f &color) { for (int i = 0; i < width*height; i++) data[i] = color; } main.C Main code: Function references myImage.SetAllPixels(clearColor);

Constructors & Destructors class Image { public: Image(void) { width = height = 0; data = NULL; } ~Image(void) { if (data != NULL) delete[] data; int width; int height; Vec3f *data; }; Constructor: Called whenever a new instance is created Destructor: Called whenever an instance is deleted

Constructors Constructors can also take parameters Image(int w, int h) { width = w; height = h; data = new Vec3f[w*h]; } Using this constructor with stack or heap allocation: Image myImage = Image(10, 10); Image *imagePtr; imagePtr = new Image(10, 10); stack allocation heap allocation

The Copy Constructor Image(Image *img) { width = img->width; height = img->height; data = new Vec3f[width*height]; for (int i=0; i<width*height; i++) data[i] = img->data[i]; } A default copy constructor is created automatically, but it is often not what you want: Warning: if you do not create a default (void parameter) or copy constructor explicitly, they are created for you. Image(Image *img) { width = img->width; height = img->height; data = img->data; }

Passing Classes as Parameters If a class instance is passed by value, the copy constructor will be used to make a copy. bool IsImageGreen(Image img); Computationally expensive It’s much faster to pass by reference: bool IsImageGreen(Image *img); or bool IsImageGreen(Image &img);

Class Hierarchy Child classes inherit parent attributes Object3D class Object3D { Vec3f color; }; class Sphere : public Object3D { float radius; class Cone : public Object3D { float base; float height; Sphere Cone

Class Hierarchy Child classes can call parent functions Sphere::Sphere() : Object3D() { radius = 1.0; } Call the parent constructor Child classes can override parent functions class Object3D { virtual void setDefaults(void) { color = RED; } }; class Sphere : public Object3D { void setDefaults(void) { color = BLUE; radius = 1.0 } Superclass Subclass

Virtual Functions A superclass pointer can reference a subclass object Sphere *mySphere = new Sphere(); Object3D *myObject = mySphere; If a superclass has virtual functions, the correct subclass version will automatically be selected class Object3D { virtual void intersect(Ray *r, Hit *h); }; class Sphere : public Object3D { myObject->intersect(ray, hit); Superclass Subclass Actually calls Sphere::intersect

Pure Virtual Functions A pure virtual function has a prototype, but no definition. Used when a default implementation does not make sense. class Object3D { virtual void intersect(Ray *r, Hit *h) = 0; }; A class with a pure virtual function is called a pure virtual class and cannot be instantiated. (However, its subclasses can).

The main function This is where your code begins execution int main(int argc, char** argv); Number of arguments Array of strings argv[0] is the program name argv[1] through argv[argc-1] are command-line input

Coding tips Use the #define compiler directive for constants #define PI 3.14159265 #define MAX_ARRAY_SIZE 20 Use the printf or cout functions for output and debugging printf("value: %d, %f\n", myInt, myFloat); cout << "value:" << myInt << ", " << myFloat << endl; Use the assert function to test “always true” conditions assert(denominator != 0); quotient = numerator/denominator;

Coding tips After you delete an object, also set its value to NULL (This is not done for you automatically) delete myObject; myObject = NULL; This will make it easier to debug memory allocation errors assert(myObject != NULL); myObject->setColor(RED);

Segmentation fault (core dumped) Typical causes: Access outside of array bounds int intArray[10]; intArray[10] = 6837; Image *img; img->SetAllPixels(ClearColor); Attempt to access a NULL or previously deleted pointer These errors are often very difficult to catch and can cause erratic, unpredictable behavior.

Common Pitfalls void setToRed(Vec3f v) { v = RED; } Since v is passed by value, it will not get updated outside of The set function The fix: void setToRed(Vec3f &v) { v = RED; } or void setToRed(Vec3f *v) { *v = RED; }

Common Pitfalls Sphere* getRedSphere() { Sphere s = Sphere(1.0); s.setColor(RED); return &s; } C++ automatically deallocates stack memory when the function exits, so the returned pointer is invalid. The fix: It will then be your responsibility to delete the Sphere object later. Sphere* getRedSphere() { Sphere *s = new Sphere(1.0); s->setColor(RED); return s; }

Advanced topics Lots of advanced topics, but few will be required for this course friend or protected class members inline functions const or static functions and variables compiler directives operator overloading Vec3f& operator+(Vec3f &a, Vec3f &b);