SlideShare a Scribd company logo
1 of 26
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

Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...ssuserd6b1fd
 
Arduino coding class
Arduino coding classArduino coding class
Arduino coding classJonah Marrs
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation JavascriptRamesh Nair
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...ssuserd6b1fd
 
Python opcodes
Python opcodesPython opcodes
Python opcodesalexgolec
 
C - aptitude3
C - aptitude3C - aptitude3
C - aptitude3Srikanth
 
Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”Platonov Sergey
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)hhliu
 
TCO in Python via bytecode manipulation.
TCO in Python via bytecode manipulation.TCO in Python via bytecode manipulation.
TCO in Python via bytecode manipulation.lnikolaeva
 
C++totural file
C++totural fileC++totural file
C++totural filehalaisumit
 
How to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITHow to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITEgor Bogatov
 
C++ Programming - 11th Study
C++ Programming - 11th StudyC++ Programming - 11th Study
C++ Programming - 11th StudyChris Ohk
 
Stupid Awesome Python Tricks
Stupid Awesome Python TricksStupid Awesome Python Tricks
Stupid Awesome Python TricksBryan Helmig
 

What's hot (18)

Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
 
Arduino coding class
Arduino coding classArduino coding class
Arduino coding class
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
c programming
c programmingc programming
c programming
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
 
Python opcodes
Python opcodesPython opcodes
Python opcodes
 
C - aptitude3
C - aptitude3C - aptitude3
C - aptitude3
 
Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)
 
c programming
c programmingc programming
c programming
 
TCO in Python via bytecode manipulation.
TCO in Python via bytecode manipulation.TCO in Python via bytecode manipulation.
TCO in Python via bytecode manipulation.
 
C++ L08-Classes Part1
C++ L08-Classes Part1C++ L08-Classes Part1
C++ L08-Classes Part1
 
OpenXR 1.0 Reference Guide
OpenXR 1.0 Reference GuideOpenXR 1.0 Reference Guide
OpenXR 1.0 Reference Guide
 
C++totural file
C++totural fileC++totural file
C++totural file
 
How to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITHow to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJIT
 
C++ Programming - 11th Study
C++ Programming - 11th StudyC++ Programming - 11th Study
C++ Programming - 11th Study
 
Stupid Awesome Python Tricks
Stupid Awesome Python TricksStupid Awesome Python Tricks
Stupid Awesome Python Tricks
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
 

Viewers also liked

ADVANCED FEATURES OF C++
ADVANCED FEATURES OF C++ADVANCED FEATURES OF C++
ADVANCED FEATURES OF C++NITHYA KUMAR
 
2015 Upload Campaigns Calendar - SlideShare
2015 Upload Campaigns Calendar - SlideShare2015 Upload Campaigns Calendar - SlideShare
2015 Upload Campaigns Calendar - SlideShareSlideShare
 
What to Upload to SlideShare
What to Upload to SlideShareWhat to Upload to SlideShare
What to Upload to SlideShareSlideShare
 
Getting Started With SlideShare
Getting Started With SlideShareGetting Started With SlideShare
Getting Started With SlideShareSlideShare
 

Viewers also liked (6)

Dsp
Dsp Dsp
Dsp
 
ADVANCED FEATURES OF C++
ADVANCED FEATURES OF C++ADVANCED FEATURES OF C++
ADVANCED FEATURES OF C++
 
How to Use Slideshare
How to Use SlideshareHow to Use Slideshare
How to Use Slideshare
 
2015 Upload Campaigns Calendar - SlideShare
2015 Upload Campaigns Calendar - SlideShare2015 Upload Campaigns Calendar - SlideShare
2015 Upload Campaigns Calendar - SlideShare
 
What to Upload to SlideShare
What to Upload to SlideShareWhat to Upload to SlideShare
What to Upload to SlideShare
 
Getting Started With SlideShare
Getting Started With SlideShareGetting Started With SlideShare
Getting Started With SlideShare
 

Similar to Advance features of C++

Dotnet unit 4
Dotnet unit 4Dotnet unit 4
Dotnet unit 4007laksh
 
openFrameworks 007 - 3D
openFrameworks 007 - 3DopenFrameworks 007 - 3D
openFrameworks 007 - 3Droxlu
 
PVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error ExamplesPVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error ExamplesAndrey Karpov
 
Lecture 9_Classes.pptx
Lecture 9_Classes.pptxLecture 9_Classes.pptx
Lecture 9_Classes.pptxNelyJay
 
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)PROIDEA
 
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...DroidConTLV
 
Data structures KTU chapter2.PPT
Data structures KTU chapter2.PPTData structures KTU chapter2.PPT
Data structures KTU chapter2.PPTAlbin562191
 
in this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdfin this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdfmichardsonkhaicarr37
 
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : NotesCUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : NotesSubhajit Sahu
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.pptDeepVala5
 
Csphtp1 09
Csphtp1 09Csphtp1 09
Csphtp1 09HUST
 

Similar to Advance features of C++ (20)

C++ programs
C++ programsC++ programs
C++ programs
 
Dotnet unit 4
Dotnet unit 4Dotnet unit 4
Dotnet unit 4
 
Op ps
Op psOp ps
Op ps
 
openFrameworks 007 - 3D
openFrameworks 007 - 3DopenFrameworks 007 - 3D
openFrameworks 007 - 3D
 
PVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error ExamplesPVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error Examples
 
662305 10
662305 10662305 10
662305 10
 
Lecture 9_Classes.pptx
Lecture 9_Classes.pptxLecture 9_Classes.pptx
Lecture 9_Classes.pptx
 
Chapter2
Chapter2Chapter2
Chapter2
 
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
 
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
 
Chapter2
Chapter2Chapter2
Chapter2
 
Data structures KTU chapter2.PPT
Data structures KTU chapter2.PPTData structures KTU chapter2.PPT
Data structures KTU chapter2.PPT
 
in this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdfin this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdf
 
C++ L11-Polymorphism
C++ L11-PolymorphismC++ L11-Polymorphism
C++ L11-Polymorphism
 
Memory Management In C++
Memory Management In C++Memory Management In C++
Memory Management In C++
 
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : NotesCUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.ppt
 
Chp4(ref dynamic)
Chp4(ref dynamic)Chp4(ref dynamic)
Chp4(ref dynamic)
 
Csphtp1 09
Csphtp1 09Csphtp1 09
Csphtp1 09
 
3433 Ch09 Ppt
3433 Ch09 Ppt3433 Ch09 Ppt
3433 Ch09 Ppt
 

Recently uploaded

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdfssuserdda66b
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 

Recently uploaded (20)

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 

Advance features of C++

  • 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: info@tgouwp.edu

Editor's Notes

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