C++TutorialRob JagnowThis tutorial will be best for students who have at least had some exposure to Java or another comparable programming language.Overview•Pointers•Arrays and strings•Parameter passing•Class basics•Constructors & destructors•Class Hierarchy•Virtual Functions•Coding tips•Advanced topicsAdvanced topics: friends, protected, inline functions, const, static, virtual inheritance, pure virtual function (e.g. Intersect(ray, hit) = 0), class hierarchy.PointersCreate a pointerint*intPtr;intPtr= new int;*intPtr= 6837;delete intPtr;intotherVal= 5;intPtr= &otherVal;Allocate memorySet value at given address6837*intPtrintPtr0x0050DeallocatememoryChange intPtrto point toa new location5*intPtrotherValintPtr0x0054&otherValArraysStack allocationintintArray[10];intArray[0] = 6837;int*intArray;intArray= new int[10];intArray[0] = 6837;...delete[] intArray;Heap allocationC++ arrays are zero-indexed.StringsA string in C++ is an array of characterschar myString[20];strcpy(myString, "Hello World");Strings are terminated with the NULLor '\0'charactermyString[0] = 'H';myString[1] = 'i';myString[2] = '\0';printf("%s", myString);output: HiParameter Passingpass by valueMake a local copy of a& bintadd(inta, intb) {return a+b;}inta, b, sum;sum = add(a, b);pass by referencePass pointers that reference a& b. Changes made to aor bwill be reflected outside the addroutineintadd(int*a, int*b) {return *a + *b;}inta, b, sum;sum = add(&a, &b);Parameter Passingpass by reference –alternate notationintadd(int&a, int&b) {return a+b;}inta, b, sum;sum = add(a, b);Class Basics#ifndef_IMAGE_H_#define _IMAGE_H_#include #include "vectors.h“class Image {public:...private:...};#endifInclude a library fileInclude a local filePrevents multiple referencesVariables and functionsaccessible from anywhereVariables and functions accessibleonly from within this classNote that “private:” is the defaultCreating an instanceImage myImage;myImage.SetAllPixels(ClearColor);Stack allocationHeap allocationImage *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 Strategyimage.hHeader file: Class definition & function prototypesvoid SetAllPixels(constVec3f &color);image.C.C file: Full function definitionsvoid Image::SetAllPixels(constVec3f &color) {for (inti = 0; i < width*height; i++)data[i] = color;}main.CMain code: Function referencesmyImage.SetAllPixels(clearColor);Constructors & Destructorsclass Image {public:Image(void) {width = height = 0;data = NULL;}~Image(void) {if (data != NULL)delete[] data;}intwidth;intheight;Vec3f *data;};Constructor:Called whenever a newinstance is createdDestructor:Called whenever aninstance is deletedConstructorsConstructors can also take parametersImage(intw, inth) {width = w;height = h;data = new Vec3f[w*h];}Using this constructor with stack or heap allocation:stack allocationImage myImage= Image(10, 10);Image *imagePtr;imagePtr= new Image(10, 10);heap allocationThe Copy ConstructorImage(Image*img) {width = img->width;height = img->height;data = new Vec3f[width*height];for (inti=0; iwidth;height = img->height;data = img->data;}A default copy constructor is created automatically,but it is usually not what you want:Warning: if you do not create a default (void parameter) or copyconstructor explicitly, they are created for you.Passing Classes as ParametersIf a class instance is passed by reference, the copy constructorwill be used to make a copy.boolIsImageGreen(Imageimg);Computationally expensiveIt’s much faster to pass by reference:boolIsImageGreen(Image*img);orboolIsImageGreen(Image&img);Class HierarchyChild classes inherit parent attributesObject3DSphereConeclass Object3D {Vec3f color;};class Sphere : public Object3D {float radius;};class Cone : public Object3D {float base;float height;};Class HierarchyChild classes can callparent functionsSphere::Sphere() : Object3D() {radius = 1.0;}Call the parent constructorChild classes can overrideparent functionsclass Object3D {virtual void setDefaults(void) {color = RED; }};class Sphere : public Object3D {void setDefaults(void) {color = BLUE;radius = 1.0 }};Virtual FunctionsA superclasspointer can reference a subclass objectSphere *mySphere= new Sphere();Object3D *myObject= mySphere;If a superclasshas virtual functions, the correct subclass version will automatically be selectedclass Object3D {virtual void intersect(Vec3f *ray, Vec3f *hit);};class Sphere : public Object3D {virtual void intersect(Vec3f *ray, Vec3f *hit);};myObject->intersect(ray, hit);SuperclassSubclassActually calls Sphere::intersectThe mainfunctionThis is where your code begins executionintmain(intargc, char** argv);Number of argumentsArray of stringsargv[0]is the program nameargv[1]through argv[argc-1]are command-line inputCoding tipsUse the #definecompiler directive for constants#define PI 3.14159265#define sinfsinUse the printfor coutfunctions for output and debuggingprintf("value: %d, %f\n", myInt, myFloat);cout<< "value:" << myInt<< ", " << myFloat<< endl;Use the assertfunction to test “always true” conditionsassert(denominator!= 0);quotient = numerator/denominator;“Segmentation fault (core dumped)”Typical causes:Access outside ofarray boundsintintArray[10];intArray[10] = 6837;Image *img;img->SetAllPixels(ClearColor);Attempt to accessa NULL or previouslydeleted pointerThese errors are often very difficult to catch and can cause erratic, unpredictable behavior. Advanced topicsLots of advanced topics, but few will be required for this course•friendor protectedclass members•inline functions•constor staticfunctions and variables•purevirtual functionsvirtual void Intersect(Ray&r, Hit &h) = 0;•compiler directives•operator overloadingVec3f& operator+(Vec3f &a, Vec3f &b);
Description
In computer graphics Algorithems have to be developed in c language or C++ language.Hence one need to underdtand throughly c C++.
“Prof. Frédo Durand & Prof. Barbara , 6.837-2 C++ Tutorial, 6.837 Computer Graphics , Electrical Engineering and Computer Science, Engineering, Massachusetts Institute of Technology: MIT Open Course Ware,http://ocw.mit.edu (22-08-2011).License: Creative Commons BY-NC-SA: http://ocw.mit.edu/terms/#cc".
Presentation Transcript
Your Facebook Friends on WizIQ