SlideShare a Scribd company logo
The Global Open University
Nagaland
C++
Special guide of tricks in
 Pointers
 Arrays and strings
 Parameter passing
 Class basics
 Constructors & destructors
 Class Hierarchy
 Virtual Functions
 Coding tips
 Advanced topics
int *intPtr;
intPtr = new int;
*intPtr = 6837;
delete intPtr;
int otherVal = 5;
intPtr = &otherVal;
Create a pointer
Allocate memory
Set value at given address
Change intPtr to point to
a new location
6837*intPtr
0x0050intPtr
5*intPtr
0x0054intPtr
otherVal
&otherVal
Deallocate memory
int intArray[10];
intArray[0] = 6837;
int *intArray;
intArray = new int[10];
intArray[0] = 6837;
...
delete[] intArray;
Stack allocation
Heap allocation
char myString[20];
strcpy(myString, "Hello World");
myString[0] = 'H';
myString[1] = 'i';
myString[2] = '0';
printf("%s", myString);
A string in C++ is an array of characters
Strings are terminated with the NULL or '0' character
output: Hi
int add(int a, int b) {
return a+b;
}
int a, b, sum;
sum = add(a, b);
pass by value
int add(int *a, int *b) {
return *a + *b;
}
int a, b, sum;
sum = add(&a, &b);
pass by reference
Make a local copy
of a and b
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);
pass by reference – alternate notation
#ifndef _IMAGE_H_
#define _IMAGE_H_
#include <assert.h>
#include "vectors.h“
class Image {
public:
...
private:
...
};
#endif
Include a library file
Include a local file
Prevents multiple references
Variables and functions
accessible from anywhere
Variables and functions accessible
only from within this class’s functions
Image myImage;
myImage.SetAllPixels(ClearColor);
Image *imagePtr;
imagePtr = new Image();
imagePtr->SetAllPixels(ClearColor);
...
delete imagePtr;
Stack allocation
Heap allocation
image.h Header file: Class definition & function prototypes
.C file: Full function definitions
Main code: Function references
image.C
main.C
void SetAllPixels(const Vec3f &color);
void Image::SetAllPixels(const Vec3f &color) {
for (int i = 0; i < width*height; i++)
data[i] = color;
}
myImage.SetAllPixels(clearColor);
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
Image(int w, int h) {
width = w;
height = h;
data = new Vec3f[w*h];
}
Constructors can also take parameters
Image myImage = Image(10, 10);
Image *imagePtr;
imagePtr = new Image(10, 10);
Using this constructor with stack or heap allocation:
stack allocation
heap allocation
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];
}
Image(Image *img) {
width = img->width;
height = img->height;
data = img->data;
}
A default copy constructor is created automatically,
but it is often not what you want:
bool IsImageGreen(Image img);
If a class instance is passed by value, the copy constructor will
be used to make a copy.
Computationally expensive
bool IsImageGreen(Image *img);
It’s much faster to pass by reference:
bool IsImageGreen(Image &img);
or
class Object3D {
Vec3f color;
};
class Sphere : public Object3D {
float radius;
};
class Cone : public Object3D {
float base;
float height;
};
Child classes inherit parent attributes
Object3D
Sphere Cone
Sphere::Sphere() : Object3D() {
radius = 1.0;
}
Child classes can call parent functions
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 }
};
Call the parent constructor
SuperclassSubclass
class Object3D {
virtual void intersect(Ray *r, Hit *h);
};
class Sphere : public Object3D {
virtual void intersect(Ray *r, Hit *h);
};
myObject->intersect(ray, hit);
If a superclass has virtual functions, the correct subclass
version will automatically be selected
Sphere *mySphere = new Sphere();
Object3D *myObject = mySphere;
A superclass pointer can reference a subclass object
Actually calls
Sphere::intersect
SuperclassSubclass
class Object3D {
virtual void intersect(Ray *r, Hit *h) = 0;
};
A pure virtual function has a prototype, but no definition.
Used when a default implementation does not make sense.
A class with a pure virtual function is called a pure
virtual class and cannot be instantiated. (However, its
subclasses can).
int main(int argc, char** argv);
This is where your code begins execution
Number of
arguments
Array of
strings
argv[0] is the program name
argv[1] through argv[argc-1] are command-line input
#define PI 3.14159265
#define MAX_ARRAY_SIZE 20
Use the #define compiler directive for constants
printf("value: %d, %fn", myInt, myFloat);
cout << "value:" << myInt << ", " << myFloat << endl;
Use the printf or cout functions for output and debugging
assert(denominator != 0);
quotient = numerator/denominator;
Use the assert function to test “always true” conditions
delete myObject;
myObject = NULL;
After you delete an object, also set its value to NULL
(This is not done for you automatically)
This will make it easier to debug memory allocation errors
assert(myObject != NULL);
myObject->setColor(RED);
int intArray[10];
intArray[10] = 6837;
Image *img;
img->SetAllPixels(ClearColor);
Typical causes:
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.
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;
}
void setToRed(Vec3f *v) {
*v = RED;
}
or
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:
Sphere* getRedSphere() {
Sphere *s = new Sphere(1.0);
s->setColor(RED);
return s;
}
It will then be your
responsibility to
delete the Sphere
object later.
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);
This material has been taken from Online
Certificate course on C++ from Global Open
University Online certification programme. For
complete course material visit:
http://tgouwp.eduhttp://tgouwp.edu
About Global Open University :
The global open university is now offering certification courses in
various fields. Even you can study, give exam from comfort of
your home. These are short term and totally online courses. For
more details you can visit:
Email id: info@tgouwp.edu

More Related Content

What's hot (20)

PDF
20140531 serebryany lecture02_find_scary_cpp_bugs
Computer Science Club
 
PDF
OpenGL 4.4 Reference Card
The Khronos Group Inc.
 
PDF
Lambda expressions in C++
Dimitrios Platis
 
PDF
OpenXR 1.0 Reference Guide
The Khronos Group Inc.
 
PPTX
Academy PRO: ES2015
Binary Studio
 
PDF
20140531 serebryany lecture01_fantastic_cpp_bugs
Computer Science Club
 
PDF
Dynamic C++ ACCU 2013
aleks-f
 
PDF
Kristhyan kurtlazartezubia evidencia1-metodosnumericos
KristhyanAndreeKurtL
 
PDF
Writing SOLID C++ [gbgcpp meetup @ Zenseact]
Dimitrios Platis
 
PDF
Recursion to iteration automation.
Russell Childs
 
PPT
PDBC
Sunil OS
 
KEY
openFrameworks 007 - GL
roxlu
 
PDF
Imugi: Compiler made with Python
Han Lee
 
PPTX
Chapter 7 functions (c)
hhliu
 
PDF
Arduino coding class
Jonah Marrs
 
PDF
C++ L01-Variables
Mohammad Shaker
 
PDF
Bind me if you can
Ovidiu Farauanu
 
PDF
glTF 2.0 Reference Guide
The Khronos Group Inc.
 
PPT
FP 201 - Unit4 Part 2
rohassanie
 
PPT
OOP v3
Sunil OS
 
20140531 serebryany lecture02_find_scary_cpp_bugs
Computer Science Club
 
OpenGL 4.4 Reference Card
The Khronos Group Inc.
 
Lambda expressions in C++
Dimitrios Platis
 
OpenXR 1.0 Reference Guide
The Khronos Group Inc.
 
Academy PRO: ES2015
Binary Studio
 
20140531 serebryany lecture01_fantastic_cpp_bugs
Computer Science Club
 
Dynamic C++ ACCU 2013
aleks-f
 
Kristhyan kurtlazartezubia evidencia1-metodosnumericos
KristhyanAndreeKurtL
 
Writing SOLID C++ [gbgcpp meetup @ Zenseact]
Dimitrios Platis
 
Recursion to iteration automation.
Russell Childs
 
PDBC
Sunil OS
 
openFrameworks 007 - GL
roxlu
 
Imugi: Compiler made with Python
Han Lee
 
Chapter 7 functions (c)
hhliu
 
Arduino coding class
Jonah Marrs
 
C++ L01-Variables
Mohammad Shaker
 
Bind me if you can
Ovidiu Farauanu
 
glTF 2.0 Reference Guide
The Khronos Group Inc.
 
FP 201 - Unit4 Part 2
rohassanie
 
OOP v3
Sunil OS
 

Similar to Cppt 101102014428-phpapp01 (20)

PDF
CS225_Prelecture_Notes 2nd
Edward Chen
 
PPTX
C traps and pitfalls for C++ programmers
Richard Thomson
 
PPTX
#OOP_D_ITS - 2nd - C++ Getting Started
Hadziq Fabroyir
 
PPT
Link list
Malainine Zaid
 
PDF
00-intro-to-classes.pdf
TamiratDejene1
 
PDF
麻省理工C++公开教学课程(二)
ProCharm
 
PPT
oop objects_classes
sidra tauseef
 
PPTX
#OOP_D_ITS - 3rd - Pointer And References
Hadziq Fabroyir
 
PPTX
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Abu Saleh
 
PDF
Object Oriented Programming (OOP) using C++ - Lecture 4
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PPT
CppTutorial.ppt
HODZoology3
 
PPT
C++tutorial
dips17
 
PPTX
Pointers, virtual function and polymorphism
lalithambiga kamaraj
 
PDF
Bjarne essencegn13
Hunde Gurmessa
 
PDF
Effective Object Oriented Design in Cpp
CodeOps Technologies LLP
 
PPTX
C++ Introduction brown bag
Jacob Green
 
PPT
Cpp tutorial
Vikas Sharma
 
PPTX
Chapter 2 OOP using C++ (Introduction).pptx
FiraolGadissa
 
PDF
How to make a large C++-code base manageable
corehard_by
 
PDF
L10
lksoo
 
CS225_Prelecture_Notes 2nd
Edward Chen
 
C traps and pitfalls for C++ programmers
Richard Thomson
 
#OOP_D_ITS - 2nd - C++ Getting Started
Hadziq Fabroyir
 
Link list
Malainine Zaid
 
00-intro-to-classes.pdf
TamiratDejene1
 
麻省理工C++公开教学课程(二)
ProCharm
 
oop objects_classes
sidra tauseef
 
#OOP_D_ITS - 3rd - Pointer And References
Hadziq Fabroyir
 
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Abu Saleh
 
Object Oriented Programming (OOP) using C++ - Lecture 4
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
CppTutorial.ppt
HODZoology3
 
C++tutorial
dips17
 
Pointers, virtual function and polymorphism
lalithambiga kamaraj
 
Bjarne essencegn13
Hunde Gurmessa
 
Effective Object Oriented Design in Cpp
CodeOps Technologies LLP
 
C++ Introduction brown bag
Jacob Green
 
Cpp tutorial
Vikas Sharma
 
Chapter 2 OOP using C++ (Introduction).pptx
FiraolGadissa
 
How to make a large C++-code base manageable
corehard_by
 
L10
lksoo
 
Ad

More from Getachew Ganfur (13)

PPT
Stacks queues-1220971554378778-9
Getachew Ganfur
 
PDF
Sienna6bst 120411102353-phpapp02
Getachew Ganfur
 
PDF
Programmingwithc 131017034813-phpapp01
Getachew Ganfur
 
PDF
Lect02 120929183452-phpapp02
Getachew Ganfur
 
PDF
Labmanualc2ndedition2 2-121115034959-phpapp02
Getachew Ganfur
 
PDF
His162013 140529214456-phpapp01
Getachew Ganfur
 
PPT
Fundamentalsofdatastructures 110501104205-phpapp02
Getachew Ganfur
 
PPTX
Ds 111011055724-phpapp01
Getachew Ganfur
 
DOCX
Document(1)
Getachew Ganfur
 
DOC
Datastructurenotes 100627004340-phpapp01
Getachew Ganfur
 
PPTX
Datastructureanditstypes 110410094332-phpapp02
Getachew Ganfur
 
PPT
Ccourse 140618093931-phpapp02
Getachew Ganfur
 
DOCX
1to5 4th
Getachew Ganfur
 
Stacks queues-1220971554378778-9
Getachew Ganfur
 
Sienna6bst 120411102353-phpapp02
Getachew Ganfur
 
Programmingwithc 131017034813-phpapp01
Getachew Ganfur
 
Lect02 120929183452-phpapp02
Getachew Ganfur
 
Labmanualc2ndedition2 2-121115034959-phpapp02
Getachew Ganfur
 
His162013 140529214456-phpapp01
Getachew Ganfur
 
Fundamentalsofdatastructures 110501104205-phpapp02
Getachew Ganfur
 
Ds 111011055724-phpapp01
Getachew Ganfur
 
Document(1)
Getachew Ganfur
 
Datastructurenotes 100627004340-phpapp01
Getachew Ganfur
 
Datastructureanditstypes 110410094332-phpapp02
Getachew Ganfur
 
Ccourse 140618093931-phpapp02
Getachew Ganfur
 
1to5 4th
Getachew Ganfur
 
Ad

Cppt 101102014428-phpapp01

  • 1. The Global Open University Nagaland C++ Special guide of tricks in
  • 2.  Pointers  Arrays and strings  Parameter passing  Class basics  Constructors & destructors  Class Hierarchy  Virtual Functions  Coding tips  Advanced topics
  • 3. int *intPtr; intPtr = new int; *intPtr = 6837; delete intPtr; int otherVal = 5; intPtr = &otherVal; Create a pointer Allocate memory Set value at given address Change intPtr to point to a new location 6837*intPtr 0x0050intPtr 5*intPtr 0x0054intPtr otherVal &otherVal Deallocate memory
  • 4. int intArray[10]; intArray[0] = 6837; int *intArray; intArray = new int[10]; intArray[0] = 6837; ... delete[] intArray; Stack allocation Heap allocation
  • 5. char myString[20]; strcpy(myString, "Hello World"); myString[0] = 'H'; myString[1] = 'i'; myString[2] = '0'; printf("%s", myString); A string in C++ is an array of characters Strings are terminated with the NULL or '0' character output: Hi
  • 6. int add(int a, int b) { return a+b; } int a, b, sum; sum = add(a, b); pass by value int add(int *a, int *b) { return *a + *b; } int a, b, sum; sum = add(&a, &b); pass by reference Make a local copy of a and b Pass pointers that reference a and b. Changes made to a or b will be reflected outside the add routine
  • 7. int add(int &a, int &b) { return a+b; } int a, b, sum; sum = add(a, b); pass by reference – alternate notation
  • 8. #ifndef _IMAGE_H_ #define _IMAGE_H_ #include <assert.h> #include "vectors.h“ class Image { public: ... private: ... }; #endif Include a library file Include a local file Prevents multiple references Variables and functions accessible from anywhere Variables and functions accessible only from within this class’s functions
  • 9. Image myImage; myImage.SetAllPixels(ClearColor); Image *imagePtr; imagePtr = new Image(); imagePtr->SetAllPixels(ClearColor); ... delete imagePtr; Stack allocation Heap allocation
  • 10. image.h Header file: Class definition & function prototypes .C file: Full function definitions Main code: Function references image.C main.C void SetAllPixels(const Vec3f &color); void Image::SetAllPixels(const Vec3f &color) { for (int i = 0; i < width*height; i++) data[i] = color; } myImage.SetAllPixels(clearColor);
  • 11. 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
  • 12. Image(int w, int h) { width = w; height = h; data = new Vec3f[w*h]; } Constructors can also take parameters Image myImage = Image(10, 10); Image *imagePtr; imagePtr = new Image(10, 10); Using this constructor with stack or heap allocation: stack allocation heap allocation
  • 13. 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]; } Image(Image *img) { width = img->width; height = img->height; data = img->data; } A default copy constructor is created automatically, but it is often not what you want:
  • 14. bool IsImageGreen(Image img); If a class instance is passed by value, the copy constructor will be used to make a copy. Computationally expensive bool IsImageGreen(Image *img); It’s much faster to pass by reference: bool IsImageGreen(Image &img); or
  • 15. class Object3D { Vec3f color; }; class Sphere : public Object3D { float radius; }; class Cone : public Object3D { float base; float height; }; Child classes inherit parent attributes Object3D Sphere Cone
  • 16. Sphere::Sphere() : Object3D() { radius = 1.0; } Child classes can call parent functions 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 } }; Call the parent constructor SuperclassSubclass
  • 17. class Object3D { virtual void intersect(Ray *r, Hit *h); }; class Sphere : public Object3D { virtual void intersect(Ray *r, Hit *h); }; myObject->intersect(ray, hit); If a superclass has virtual functions, the correct subclass version will automatically be selected Sphere *mySphere = new Sphere(); Object3D *myObject = mySphere; A superclass pointer can reference a subclass object Actually calls Sphere::intersect SuperclassSubclass
  • 18. class Object3D { virtual void intersect(Ray *r, Hit *h) = 0; }; A pure virtual function has a prototype, but no definition. Used when a default implementation does not make sense. A class with a pure virtual function is called a pure virtual class and cannot be instantiated. (However, its subclasses can).
  • 19. int main(int argc, char** argv); This is where your code begins execution Number of arguments Array of strings argv[0] is the program name argv[1] through argv[argc-1] are command-line input
  • 20. #define PI 3.14159265 #define MAX_ARRAY_SIZE 20 Use the #define compiler directive for constants printf("value: %d, %fn", myInt, myFloat); cout << "value:" << myInt << ", " << myFloat << endl; Use the printf or cout functions for output and debugging assert(denominator != 0); quotient = numerator/denominator; Use the assert function to test “always true” conditions
  • 21. delete myObject; myObject = NULL; After you delete an object, also set its value to NULL (This is not done for you automatically) This will make it easier to debug memory allocation errors assert(myObject != NULL); myObject->setColor(RED);
  • 22. int intArray[10]; intArray[10] = 6837; Image *img; img->SetAllPixels(ClearColor); Typical causes: 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.
  • 23. 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; } void setToRed(Vec3f *v) { *v = RED; } or
  • 24. 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: Sphere* getRedSphere() { Sphere *s = new Sphere(1.0); s->setColor(RED); return s; } It will then be your responsibility to delete the Sphere object later.
  • 25. 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);
  • 26. This material has been taken from Online Certificate course on C++ from Global Open University Online certification programme. For complete course material visit: http://tgouwp.eduhttp://tgouwp.edu About Global Open University : The global open university is now offering certification courses in various fields. Even you can study, give exam from comfort of your home. These are short term and totally online courses. For more details you can visit: Email id: [email protected]

Editor's Notes

  • #3: Advanced topics: friends, protected, inline functions, const, static, virtual inheritance, pure virtual function (e.g. Intersect(ray, hit) = 0), class hierarchy.
  • #5: C++ arrays are zero-indexed.
  • #9: Note that “private:” is the default
  • #10: Stack allocation: Constructor and destructor called automatically when the function is entered and exited. Heap allocation: Constructor and destructor must be called explicitly.
  • #14: Warning: if you do not create a default (void parameter) or copy constructor explicitly, they are created for you.