Presentation is loading. Please wait.

Presentation is loading. Please wait.

Part 1- C++ Class Features

Similar presentations


Presentation on theme: "Part 1- C++ Class Features"— Presentation transcript:

1 Part 1- C++ Class Features
Review of Pointers Arrays and strings Parameter passing Review some Class basics Constructors & destructors Class Hierarchy Virtual Functions Advanced topics: friends, protected, inline functions, const, static, virtual inheritance, pure virtual function (e.g. Intersect(ray, hit) = 0), class hierarchy.

2 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

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

4 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

5 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);

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

7 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

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

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

10 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

11 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

12 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; }

13 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);

14 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

15 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

16 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

17 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).

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

19 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);

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

21 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; }

22 Common Pitfalls Sphere* getRedSphere() { Sphere s = Sphere(1.0); s.setColor(RED); return &s; } C++ automatically de-allocates 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; }

23 Part II - More C++ Concepts
Operator overloading Friend Function The “this” Operator

24 Operator overloading Programmer can use some operator symbols to define special member functions of a class Provides convenient notations for object behaviors

25 Why Operator Overloading
int i, j, k; // integers float m, n, p; // floats k = i + j; // integer addition and assignment p = m + n; // floating addition and assignment The compiler overloads the + operator for built-in integer and float types by default, producing integer addition with i+j, and floating addition with m+n. We can make object operation look like individual int variable operation, using operator functions Complex a,b,c; c = a + b;

26 Operator Overloading Syntax
Examples: operator+ operator- operator* operator/ Syntax is: --- operator is a function is one of C++ operator symbols (+, -, =, etc..)

27 Example of Operator Overloading
class CStr { char *pData; int nLength; public: // … void cat(char *s); CStr operator+(CStr str1, CStr str2); CStr operator+(CStr str, char *s); CStr operator+(char *s, CStr str); //accessors char* get_Data(); int get_Len(); }; void CStr::cat(char *s) { int n; char *pTemp; n=strlen(s); if (n==0) return; pTemp=new char[n+nLength+1]; if (pData) strcpy(pTemp,pData); strcat(pTemp,s); pData=pTemp; nLength+=n; }

28 The Addition (+) Operator
CStr CStr::operator+(CStr str1, CStr str2) { CStr new_string(str1); //call the copy constructor to initialize an //entirely new CStr object with the first //operand new_string.cat(str2.get_Data()); //concatenate the second operand onto the //end of new_string return new_string; //call copy constructor to create a copy of //the return value new_string } strcat(str1,str2) strlen(str1)+strlen(str2) new_string str1 strlen(str1)

29 How does it work? “John Johnson” name CStr first(“John”);
CStr last(“Johnson”); CStr name(first+last); CStr CStr::operator+(CStr str1,CStr str2) { CStr new_string(str1); new_string.cat(str2.get()); return new_string; } “John Johnson” name Copy constructor Temporary CStr object

30 Implementing Operator Overloading
Two ways: Implemented as member functions Implemented as non-member or Friend functions the operator function may need to be declared as a friend if it requires access to protected or private data Expression translates into a function call if this function is defined within class obj1 if this function is defined outside the class obj1

31 Implementing Operator Overloading
Defined as a non-member function class Complex { ... public: double real() { return _real; } //need access functions double imag() { return _imag; } }; c = a+b; c = operator+ (a, b); Complex operator +(Complex &op1, Complex &op2) { double real = op1.real() + op2.real(), imag = op1.imag() + op2.imag(); return(Complex(real, imag)); }

32 Implementing Operator Overloading
Defined as a friend function class Complex { ... public: friend Complex operator +( const Complex &, const Complex & ); }; c = a+b; c = operator+ (a, b); Complex operator +(Complex &op1, Complex &op2) { double real = op1._real + op2._real, imag = op1._imag + op2._imag; return(Complex(real, imag)); }

33 Ordinary Member Functions, Static Functions and Friend Functions
The function can access the private part of the class definition The function is in the scope of the class The function must be invoked on an object Which of these are true about the different functions?

34 What is ‘Friend’? Friend declarations introduce extra coupling between classes Once an object is declared as a friend, it has access to all non-public members as if they were public Access is unidirectional If B is designated as friend of A, B can access A’s non-public members; A cannot access B’s A friend function of a class is defined outside of that class's scope

35 More about ‘Friend’ The major use of friends is
to provide more efficient access to data members than the function call to accommodate operator functions with easy access to private data members Friends can have access to everything, which defeats data hiding, so use them carefully Friends have permission to change the internal state from outside the class. Always recommend use member functions instead of friends to change state

36 Assignment Operator Assignment between objects of the same type is always supported the compiler supplies a hidden assignment function if you don’t write your own one same problem as with the copy constructor - the member by member copying Syntax: class& class::operator=(const class &arg) { //… }

37 Example: Assignment for CStr class
Assignment operator for CStr: CStr& CStr::operator=(const CStr & source) Return type - a reference to (address of) a CStr object Argument type - a reference to a CStr object (since it is const, the function cannot modify it) CStr& CStr::operator=(const CStr &source){ //... Do the copying return *this; } Assignment function is called as a member function of the left operand =>Return the object itself str1=str2; str1.operator=(str2) Copy Assignment is different from Copy Constructor

38 The “this” pointer this pData nLength
Within a member function, the this keyword is a pointer to the current object, i.e. the object through which the function was called C++ passes a hidden this pointer whenever a member function is called Within a member function definition, there is an implicit use of this pointer for references to data members this Data member reference Equivalent to pData this->pData nLength this->nLength pData nLength CStr object (*this)

39 Overloading stream-insertion and stream-extraction operators
In fact, cout<< or cin>> are operator overloading built in C++ standard lib of iostream.h, using operator "<<" and ">>" cout and cin are the objects of ostream and istream classes, respectively We can add a friend function which overloads the operator << friend ostream& operator<< (ostream &os, const Date &d); ostream& operator<<(ostream &os, const Date &d) { os<<d.month<<“/”<<d.day<<“/”<<d.year; return os; } cout<< d1; //overloaded operator cout object of ostream

40 Overloading stream-insertion and stream-extraction operators
We can also add a friend function which overloads the operator >> friend istream& operator>> (istream &in, Date &d); istream& operator>> (istream &in, Date &d) { char mmddyy[9]; in >> mmddyy; // check if valid data entered if (d.set(mmddyy)) return in; cout<< "Invalid date format: "<<d<<endl; exit(-1); } cin object of istream cin >> d1;

41 Overloaded yet? Operator overloading provides convenient notations for object behaviors There are three ways to implement operator overloading member functions normal non-member functions friend functions


Download ppt "Part 1- C++ Class Features"

Similar presentations


Ads by Google