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.

Slides:



Advertisements
Similar presentations
Object-Oriented Programming Session 9 Course : T Programming Language Concept Year : February 2011.
Advertisements

Chapter 4 Constructors and Destructors. Objectives Constructors – introduction and features The zero-argument constructor Parameterized constructors Creating.
Basic Java Constructs and Data Types – Nuts and Bolts
1 Inheritance Classes and Subclasses Or Extending a Class.
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Addition Facts
Object Oriented Programming with Java
Color Templates Software Engineering Module: Core of Java Topic: Constructors TALENTSPRINT | © Copyright 2012.
User Defined Functions
1 Chapter Eleven Arrays. 2 A Motivating Example main( ) { int n0, n1, n2, n3, n4; scanf(“%d”, &n0); scanf(“%d”, &n1); scanf(“%d”, &n2); scanf(“%d”, &n3);
Object-Oriented Programming. 2 An object, similar to a real-world object, is an entity with certain properties, and with the ability to react in certain.
Purpose : To convert this string to a new character array. Return Type : char[ ] Parameters : none Declaration : public char[ ] toCharArray() Returns.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 14 - Advanced C Topics Outline 14.1Introduction 14.2Redirecting Input/Output on UNIX and DOS Systems.
Addition 1’s to 20.
EC-111 Algorithms & Computing Lecture #11 Instructor: Jahan Zeb Department of Computer Engineering (DCE) College of E&ME NUST.
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14: More About Classes.
Copyright © 2012 Pearson Education, Inc. Chapter 14: More About Classes.
Dynamic Memory Allocation in C.  What is Memory What is Memory  Memory Allocation in C Memory Allocation in C  Difference b\w static memory allocation.
Web Application Development Slides Credit Umair Javed LUMS.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Chapter 7 Process Environment Chien-Chung Shen CIS, UD
CIS 101: Computer Programming and Problem Solving Lecture10 Usman Roshan Department of Computer Science NJIT.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
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++ Tutorial Rob Jagnow. Overview Pointers Arrays and strings Parameter passing Class basics Constructors & destructors Class Hierarchy Virtual Functions.
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++
CSE 333 – SECTION 4. Overview Pointers vs. references Const Classes, constructors, new, delete, etc. More operator overloading.
Data Structures Using C++ 2E Chapter 3 Pointers and Array-Based Lists.
Recap, Test 1 prep, Composition and Inheritance. Dates Test 1 – 12 th of March Assignment 1 – 20 th of March.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
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+
CPSC 252 Dynamic Memory Allocation Page 1 Dynamic memory allocation Our first IntVector class has some serious limitations the capacity is fixed at MAX_SIZE.
Data Structures Using C++ 2E Chapter 3 Pointers. Data Structures Using C++ 2E2 Objectives Learn about the pointer data type and pointer variables Explore.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Inheritance Chapter 10 Programs built from objects/instances of classes An O.O. approach – build on earlier work. Use classes in library and ones you have.
More C++ Features True object initialisation
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.
C By Example 1 The assumption is that you know Java and need to extend that knowledge so you can program in C. 1. Hello world 2. declarations 3. pass by.
W 4 L 1 sh 1 LessonSubjectBook Week 4 lesson 1Class, copy-constructorH ; p197 – 226 Week 4 lesson 2Operators 1H ; p237 – 254 Week 5 lesson.
Functions & Pointers in C Jordan Erenrich
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.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
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.
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.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
Object-Oriented programming in C++ Classes as units of encapsulation Information Hiding Inheritance polymorphism and dynamic dispatching Storage management.
Chapter 7 Process Environment Chien-Chung Shen CIS/UD
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,
Function: Declaration
C++ in 90 minutes.
C++ Tutorial Rob Jagnow
Part 1- C++ Class Features
Functions Reasons Concepts Passing arguments to a function
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
Presentation transcript:

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.

2 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.

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

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

5 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

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

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

8 Class Basics #ifndef_IMAGE_H Prevents multiple references #define _IMAGE_H_ #include end if Include a library file #include "vectors.h Include a local file class Image { public: Variables and functions... accessible from anywhere private: Variables and functions accessible... only from within this class }; #end if Note that private: is the default

9 Creating an instance Stack 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.

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

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

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

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

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

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

16 Class Hierarchy Child classes can callparent 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 }};

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

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

19 Coding tips Use the #define compiler directive for constants #define PI #define sinf sin Use the print f 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;

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

21 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 pure virtual functions virtual void Intersect(Ray&r, Hit &h) = 0; compiler directives operator overloading Vec3f& operator+(Vec3f &a, Vec3f &b);