SlideShare uma empresa Scribd logo
1 de 23
 This tutorial offers several things.
 You’ll see some neat features of the language.
 You’ll learn the right things to google.
 You’ll find a list of useful books and web pages.
 But don’t expect too much!
 It’s complicated, and you’ll learn by doing.
 But I’ll give it my best shot, okay?
 Basic syntax
 Compiling your program
 Argument passing
 Dynamic memory
 Object-oriented programming
#include <iostream>
using namespace std;
float c(float x) {
return x*x*x;
}
int main() {
float x;
cin >> x;
cout << c(x) << endl;
return 0;
}
 Includes function definitions
for
console input and output.
 Function declaration.
 Function definition.
 Program starts here.
 Local variable declaration.
 Console input.
 Console output.
 Exit main function.
// This is main.cc
#include <iostream>
#include “mymath.h”
using namespace std;
int main() {
// ...stuff...
}
// This is mymath.h
#ifndef MYMATH
#define MYMATH
float c(float x);
float d(float x);
#endif
Functions are declared in mymat h. h, but not defined.
They are implemented separately in mymat h. cc.
main.cc mymath.cc mydraw.cc
g++ -c main.cc g++ -c mymath.cc g++ -c mydraw.cc
↓ ↓ ↓
↓ ↓ ↓
↓ ↓ ↓
g++ -o myprogram main.o mathstuff.o drawstuff.o
main.o mymath.o mydraw.o
↓
myprogram →
// This is main.cc
#include <GL/glut.h>
#include <iostream>
using namespace std;
int main() {
cout << “Hello!” << endl;
glVertex3d(1,2,3);
return 0;
}
 Include OpenGL functions.
 Include standard IO
functions.
 Long and tedious
explanation.
 Calls function from standard
IO.
 Calls function from OpenGL.
 Make object file.
 Make executable, link GLUT.
 Execute program.
% g++ -c main.cc
% g++ -o myprogram –lglut main.o
% ./myprogram
 Software engineering reasons.
 Separate interface from implementation.
 Promote modularity.
 The headers are a contract.
 Technical reasons.
 Only rebuild object files for modified source files.
 This is much more efficient for huge programs.
INCFLAGS = 
-
I/afs/csail/group/graphics/courses/6.837/public/includ
e
LINKFLAGS = 
-L/afs/csail/group/graphics/courses/6.837/public/lib 
-lglut -lvl
CFLAGS = -g -Wall -ansi
CC = g++
SRCS = main.cc parse.cc curve.cc surf.cc camera.cc
OBJS = $(SRCS:.cc=.o)
PROG = a1
all: $(SRCS) $(PROG)
$(PROG): $(OBJS)
$(CC) $(CFLAGS) $(OBJS) -o $@ $(LINKFLAGS)
.cc.o:
$(CC) $(CFLAGS) $< -c -o $@ $(INCFLAGS)
depend:
makedepend $(INCFLAGS) -Y $(SRCS)
clean:
rm $(OBJS) $(PROG)
main.o: parse.h curve.h tuple.h
# ... LOTS MORE ...
Most assignments include
makef i l es, which describe
the files, dependencies, and
steps for compilation.
You can just type make.
So you don’t have to know
the stuff from the past few
slides.
But it’s nice to know.
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
float f[n];
for (int i=0; i<n; i++)
f[i] = i;
return 0;
}
Arrays must have known
sizes at compile time.
This doesn’t compile.
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
float *f = new float[n];
for (int i=0; i<n; i++)
f[i] = i;
delete [] f;
return 0;
}
Allocate the array during
runtime using new.
No garbage collection, so
you have to delete.
Dynamic memory is
useful when you don’t
know how much space
you need.
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
vector<float> f(n);
for (int i=0; i<n; i++)
f[i] = i;
return 0;
}
STL vector is a resizable
array with all dynamic
memory handled for you.
STL has other cool stuff,
such as strings and sets.
If you can, use the STL
and avoid dynamic
memory.
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
vector<float> f;
for (int i=0; i<n; i++)
f.push_back(i);
return 0;
}
An alternative method
that does the same thing.
Methods are called with
the dot operator (same as
Java).
vector is poorly named,
it’s actually just an array.
float twice1(float x) {
return 2*x;
}
void twice2(float x) {
x = 2*x;
}
int main() {
float x = 3;
twice2(x);
cout << x << endl;
return 0;
}
 This works as expected.
 This does nothing.
 The variable is
unchanged.
vector<float>
twice(vector<float> x) {
int n = x.size();
for (int i=0; i<n; i++)
x[i] = 2*x[i];
return x;
}
int main() {
vector<float>
y(9000000);
y = twice(y);
return 0;
}
There is an incredible
amount of overhead here.
This copies a huge array
two times. It’s stupid.
Maybe the compiler’s
smart. Maybe not. Why
risk it?
void twice3(float *x) {
(*x) = 2*(*x);
}
void twice4(float &x) {
x = 2*x;
}
int main() {
float x = 3;
twice3(&x);
twice4(x);
return 0;
}
 Pass pointer by value
and
access data using
asterisk.
 Pass by reference.
 Address of variable.
 The answer is 12.
 You’ll often see objects passed by reference.
 Functions can modify objects without copying.
 To avoid copying objects (often const references).
 Pointers are kind of old school, but still useful.
 For super-efficient low-level code.
 Within objects to handle dynamic memory.
 You shouldn’t need pointers for this class.
 Use the STL instead, if at all possible.
 Classes implement objects.
 You’ve probably seen these in 6.170.
 C++ does things a little differently.
 Let’s implement a simple image object.
 Show stuff we’ve seen, like dynamic memory.
 Introduce constructors, destructors, const, and
operator overloading.
 I’ll probably make mistakes, so some debugging too.
Live Demo!
 The C++ Programming Language
 A book by Bjarne Stroustrup, inventor of C++.
 My favorite C++ book.
 The STL Programmer’s Guide
 Contains documentation for the standard template library.
 http://www.sgi.com/tech/stl/
 Java to C++ Transition Tutorial
 Probably the most helpful, since you’ve all taken 6.170.
 http://www.cs.brown.edu/courses/cs123/javatoc.shtml

Mais conteúdo relacionado

Mais procurados

Program(Output)
Program(Output)Program(Output)
Program(Output)princy75
 
C++ Programming - 2nd Study
C++ Programming - 2nd StudyC++ Programming - 2nd Study
C++ Programming - 2nd StudyChris Ohk
 
Jarmo van de Seijp Shadbox ERC223
Jarmo van de Seijp Shadbox ERC223Jarmo van de Seijp Shadbox ERC223
Jarmo van de Seijp Shadbox ERC223Jarmo van de Seijp
 
C++ Programming - 3rd Study
C++ Programming - 3rd StudyC++ Programming - 3rd Study
C++ Programming - 3rd StudyChris Ohk
 
2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.js2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.jsNoritada Shimizu
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScriptGarth Gilmour
 
C++ Programming - 11th Study
C++ Programming - 11th StudyC++ Programming - 11th Study
C++ Programming - 11th StudyChris Ohk
 
When RV Meets CEP (RV 2016 Tutorial)
When RV Meets CEP (RV 2016 Tutorial)When RV Meets CEP (RV 2016 Tutorial)
When RV Meets CEP (RV 2016 Tutorial)Sylvain Hallé
 
JavaScript - Agora nervoso
JavaScript - Agora nervosoJavaScript - Agora nervoso
JavaScript - Agora nervosoLuis Vendrame
 
C++ Programming - 14th Study
C++ Programming - 14th StudyC++ Programming - 14th Study
C++ Programming - 14th StudyChris Ohk
 
Functors, applicatives, monads
Functors, applicatives, monadsFunctors, applicatives, monads
Functors, applicatives, monadsrkaippully
 

Mais procurados (20)

Program(Output)
Program(Output)Program(Output)
Program(Output)
 
C++ Programming - 2nd Study
C++ Programming - 2nd StudyC++ Programming - 2nd Study
C++ Programming - 2nd Study
 
Wcbpijwbpij new
Wcbpijwbpij newWcbpijwbpij new
Wcbpijwbpij new
 
Rcpp11 genentech
Rcpp11 genentechRcpp11 genentech
Rcpp11 genentech
 
Jarmo van de Seijp Shadbox ERC223
Jarmo van de Seijp Shadbox ERC223Jarmo van de Seijp Shadbox ERC223
Jarmo van de Seijp Shadbox ERC223
 
C++ Programming - 3rd Study
C++ Programming - 3rd StudyC++ Programming - 3rd Study
C++ Programming - 3rd Study
 
Git avançado
Git avançadoGit avançado
Git avançado
 
2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.js2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.js
 
Functional php
Functional phpFunctional php
Functional php
 
20151224-games
20151224-games20151224-games
20151224-games
 
Implementing string
Implementing stringImplementing string
Implementing string
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScript
 
week-5x
week-5xweek-5x
week-5x
 
C++ Programming - 11th Study
C++ Programming - 11th StudyC++ Programming - 11th Study
C++ Programming - 11th Study
 
When RV Meets CEP (RV 2016 Tutorial)
When RV Meets CEP (RV 2016 Tutorial)When RV Meets CEP (RV 2016 Tutorial)
When RV Meets CEP (RV 2016 Tutorial)
 
JavaScript - Agora nervoso
JavaScript - Agora nervosoJavaScript - Agora nervoso
JavaScript - Agora nervoso
 
C++ Programming - 14th Study
C++ Programming - 14th StudyC++ Programming - 14th Study
C++ Programming - 14th Study
 
Cquestions
Cquestions Cquestions
Cquestions
 
C questions
C questionsC questions
C questions
 
Functors, applicatives, monads
Functors, applicatives, monadsFunctors, applicatives, monads
Functors, applicatives, monads
 

Destaque

Destaque (9)

Computational Complexity
Computational ComplexityComputational Complexity
Computational Complexity
 
Computational Complexity and the Evolution of Homo Sapiens
Computational Complexity and the Evolution of Homo SapiensComputational Complexity and the Evolution of Homo Sapiens
Computational Complexity and the Evolution of Homo Sapiens
 
Divide and conquer
Divide and conquerDivide and conquer
Divide and conquer
 
Divide and Conquer
Divide and ConquerDivide and Conquer
Divide and Conquer
 
Divide and Conquer - Part 1
Divide and Conquer - Part 1Divide and Conquer - Part 1
Divide and Conquer - Part 1
 
Algorithm.ppt
Algorithm.pptAlgorithm.ppt
Algorithm.ppt
 
Divide and Conquer - Part II - Quickselect and Closest Pair of Points
Divide and Conquer - Part II - Quickselect and Closest Pair of PointsDivide and Conquer - Part II - Quickselect and Closest Pair of Points
Divide and Conquer - Part II - Quickselect and Closest Pair of Points
 
The Future of Organization
The Future of OrganizationThe Future of Organization
The Future of Organization
 
WTF - Why the Future Is Up to Us - pptx version
WTF - Why the Future Is Up to Us - pptx versionWTF - Why the Future Is Up to Us - pptx version
WTF - Why the Future Is Up to Us - pptx version
 

Semelhante a Cpp tutorial

C++totural file
C++totural fileC++totural file
C++totural filehalaisumit
 
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloadingkinan keshkeh
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
Things about Functional JavaScript
Things about Functional JavaScriptThings about Functional JavaScript
Things about Functional JavaScriptChengHui Weng
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonAlex Payne
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Chris Adamson
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2goMoriyoshi Koizumi
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to JavascriptAnjan Banda
 
Performance measurement and tuning
Performance measurement and tuningPerformance measurement and tuning
Performance measurement and tuningAOE
 
Learn D3.js in 90 minutes
Learn D3.js in 90 minutesLearn D3.js in 90 minutes
Learn D3.js in 90 minutesJos Dirksen
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойSigma Software
 

Semelhante a Cpp tutorial (20)

CppTutorial.ppt
CppTutorial.pptCppTutorial.ppt
CppTutorial.ppt
 
C++ tutorial
C++ tutorialC++ tutorial
C++ tutorial
 
C++totural file
C++totural fileC++totural file
C++totural file
 
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Things about Functional JavaScript
Things about Functional JavaScriptThings about Functional JavaScript
Things about Functional JavaScript
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the Horizon
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
 
ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2go
 
C++ Overview PPT
C++ Overview PPTC++ Overview PPT
C++ Overview PPT
 
C++
C++C++
C++
 
Oops presentation
Oops presentationOops presentation
Oops presentation
 
C++ manual Report Full
C++ manual Report FullC++ manual Report Full
C++ manual Report Full
 
Effective Object Oriented Design in Cpp
Effective Object Oriented Design in CppEffective Object Oriented Design in Cpp
Effective Object Oriented Design in Cpp
 
ES6 is Nigh
ES6 is NighES6 is Nigh
ES6 is Nigh
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
Performance measurement and tuning
Performance measurement and tuningPerformance measurement and tuning
Performance measurement and tuning
 
Learn D3.js in 90 minutes
Learn D3.js in 90 minutesLearn D3.js in 90 minutes
Learn D3.js in 90 minutes
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
 

Mais de Vikas Sharma

Rules and steps for developing a software product (rsfsp) by vikas sharma
Rules and steps for developing a software product (rsfsp) by vikas sharmaRules and steps for developing a software product (rsfsp) by vikas sharma
Rules and steps for developing a software product (rsfsp) by vikas sharmaVikas Sharma
 
Office automation system for scholl (oasfs) by vikas sharma
Office automation system for scholl (oasfs) by vikas sharmaOffice automation system for scholl (oasfs) by vikas sharma
Office automation system for scholl (oasfs) by vikas sharmaVikas Sharma
 
Library and member management system (lamms) by vikas sharma
Library and member management system (lamms) by vikas sharmaLibrary and member management system (lamms) by vikas sharma
Library and member management system (lamms) by vikas sharmaVikas Sharma
 
Website optimization by vikas sharma
Website optimization by vikas sharmaWebsite optimization by vikas sharma
Website optimization by vikas sharmaVikas Sharma
 

Mais de Vikas Sharma (8)

Coloring graphs
Coloring graphsColoring graphs
Coloring graphs
 
Backtracking
Backtracking  Backtracking
Backtracking
 
Backtracking
BacktrackingBacktracking
Backtracking
 
Knapsack problem
Knapsack problemKnapsack problem
Knapsack problem
 
Rules and steps for developing a software product (rsfsp) by vikas sharma
Rules and steps for developing a software product (rsfsp) by vikas sharmaRules and steps for developing a software product (rsfsp) by vikas sharma
Rules and steps for developing a software product (rsfsp) by vikas sharma
 
Office automation system for scholl (oasfs) by vikas sharma
Office automation system for scholl (oasfs) by vikas sharmaOffice automation system for scholl (oasfs) by vikas sharma
Office automation system for scholl (oasfs) by vikas sharma
 
Library and member management system (lamms) by vikas sharma
Library and member management system (lamms) by vikas sharmaLibrary and member management system (lamms) by vikas sharma
Library and member management system (lamms) by vikas sharma
 
Website optimization by vikas sharma
Website optimization by vikas sharmaWebsite optimization by vikas sharma
Website optimization by vikas sharma
 

Último

Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
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
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 

Último (20)

Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .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
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 

Cpp tutorial

  • 1.
  • 2.  This tutorial offers several things.  You’ll see some neat features of the language.  You’ll learn the right things to google.  You’ll find a list of useful books and web pages.  But don’t expect too much!  It’s complicated, and you’ll learn by doing.  But I’ll give it my best shot, okay?
  • 3.  Basic syntax  Compiling your program  Argument passing  Dynamic memory  Object-oriented programming
  • 4. #include <iostream> using namespace std; float c(float x) { return x*x*x; } int main() { float x; cin >> x; cout << c(x) << endl; return 0; }  Includes function definitions for console input and output.  Function declaration.  Function definition.  Program starts here.  Local variable declaration.  Console input.  Console output.  Exit main function.
  • 5.
  • 6. // This is main.cc #include <iostream> #include “mymath.h” using namespace std; int main() { // ...stuff... } // This is mymath.h #ifndef MYMATH #define MYMATH float c(float x); float d(float x); #endif Functions are declared in mymat h. h, but not defined. They are implemented separately in mymat h. cc.
  • 7. main.cc mymath.cc mydraw.cc g++ -c main.cc g++ -c mymath.cc g++ -c mydraw.cc ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ g++ -o myprogram main.o mathstuff.o drawstuff.o main.o mymath.o mydraw.o ↓ myprogram →
  • 8. // This is main.cc #include <GL/glut.h> #include <iostream> using namespace std; int main() { cout << “Hello!” << endl; glVertex3d(1,2,3); return 0; }  Include OpenGL functions.  Include standard IO functions.  Long and tedious explanation.  Calls function from standard IO.  Calls function from OpenGL.  Make object file.  Make executable, link GLUT.  Execute program. % g++ -c main.cc % g++ -o myprogram –lglut main.o % ./myprogram
  • 9.  Software engineering reasons.  Separate interface from implementation.  Promote modularity.  The headers are a contract.  Technical reasons.  Only rebuild object files for modified source files.  This is much more efficient for huge programs.
  • 10. INCFLAGS = - I/afs/csail/group/graphics/courses/6.837/public/includ e LINKFLAGS = -L/afs/csail/group/graphics/courses/6.837/public/lib -lglut -lvl CFLAGS = -g -Wall -ansi CC = g++ SRCS = main.cc parse.cc curve.cc surf.cc camera.cc OBJS = $(SRCS:.cc=.o) PROG = a1 all: $(SRCS) $(PROG) $(PROG): $(OBJS) $(CC) $(CFLAGS) $(OBJS) -o $@ $(LINKFLAGS) .cc.o: $(CC) $(CFLAGS) $< -c -o $@ $(INCFLAGS) depend: makedepend $(INCFLAGS) -Y $(SRCS) clean: rm $(OBJS) $(PROG) main.o: parse.h curve.h tuple.h # ... LOTS MORE ... Most assignments include makef i l es, which describe the files, dependencies, and steps for compilation. You can just type make. So you don’t have to know the stuff from the past few slides. But it’s nice to know.
  • 11.
  • 12. #include <iostream> using namespace std; int main() { int n; cin >> n; float f[n]; for (int i=0; i<n; i++) f[i] = i; return 0; } Arrays must have known sizes at compile time. This doesn’t compile.
  • 13. #include <iostream> using namespace std; int main() { int n; cin >> n; float *f = new float[n]; for (int i=0; i<n; i++) f[i] = i; delete [] f; return 0; } Allocate the array during runtime using new. No garbage collection, so you have to delete. Dynamic memory is useful when you don’t know how much space you need.
  • 14. #include <iostream> #include <vector> using namespace std; int main() { int n; cin >> n; vector<float> f(n); for (int i=0; i<n; i++) f[i] = i; return 0; } STL vector is a resizable array with all dynamic memory handled for you. STL has other cool stuff, such as strings and sets. If you can, use the STL and avoid dynamic memory.
  • 15. #include <iostream> #include <vector> using namespace std; int main() { int n; cin >> n; vector<float> f; for (int i=0; i<n; i++) f.push_back(i); return 0; } An alternative method that does the same thing. Methods are called with the dot operator (same as Java). vector is poorly named, it’s actually just an array.
  • 16. float twice1(float x) { return 2*x; } void twice2(float x) { x = 2*x; } int main() { float x = 3; twice2(x); cout << x << endl; return 0; }  This works as expected.  This does nothing.  The variable is unchanged.
  • 17. vector<float> twice(vector<float> x) { int n = x.size(); for (int i=0; i<n; i++) x[i] = 2*x[i]; return x; } int main() { vector<float> y(9000000); y = twice(y); return 0; } There is an incredible amount of overhead here. This copies a huge array two times. It’s stupid. Maybe the compiler’s smart. Maybe not. Why risk it?
  • 18. void twice3(float *x) { (*x) = 2*(*x); } void twice4(float &x) { x = 2*x; } int main() { float x = 3; twice3(&x); twice4(x); return 0; }  Pass pointer by value and access data using asterisk.  Pass by reference.  Address of variable.  The answer is 12.
  • 19.  You’ll often see objects passed by reference.  Functions can modify objects without copying.  To avoid copying objects (often const references).  Pointers are kind of old school, but still useful.  For super-efficient low-level code.  Within objects to handle dynamic memory.  You shouldn’t need pointers for this class.  Use the STL instead, if at all possible.
  • 20.
  • 21.  Classes implement objects.  You’ve probably seen these in 6.170.  C++ does things a little differently.  Let’s implement a simple image object.  Show stuff we’ve seen, like dynamic memory.  Introduce constructors, destructors, const, and operator overloading.  I’ll probably make mistakes, so some debugging too.
  • 23.  The C++ Programming Language  A book by Bjarne Stroustrup, inventor of C++.  My favorite C++ book.  The STL Programmer’s Guide  Contains documentation for the standard template library.  http://www.sgi.com/tech/stl/  Java to C++ Transition Tutorial  Probably the most helpful, since you’ve all taken 6.170.  http://www.cs.brown.edu/courses/cs123/javatoc.shtml

Notas do Editor

  1. about as simple as it gets – just get a feel for the syntax but you’ll have more complicated programs so you want to organize better first way to do that is by separating into multiple files
  2. same program, but we’ve pulled c functions out we put it in a separate file … or rather, two separate files header file (you see on the right) declares the functions – that is, gives name, parameters, return type. but doesn’t include the implementation, which is done in a separate file. so when you code up the main program file, you can include the header file, and call the functions because in c++ you can only call functions that are declared.
  3. so here’s the basic setup you write a bunch of cc files that implement functions (or objects, as we’ll see later) the headers include the declarations of functions (or objects) include the headers in the cc files if you’re using those functions compile to object files link all object files together get program make graphics
  4. almost all c++ will make use of libraries bunch of convenient functions that you can use two libraries you’ll be using for almost assignments are glut (exp) and iostream (exp) so main here actually calls functions defined in both these libraries and here’s how we might compile
  5. why? examples of purely functional programming languages… haskell, basic scheme…
  6. why? examples of purely functional programming languages… haskell, basic scheme…
  7. why? examples of purely functional programming languages… haskell, basic scheme…
  8. why? examples of purely functional programming languages… haskell, basic scheme…
  9. So why don’t we just use the first function?
  10. So why don’t we just use the first function?
  11. So why don’t we just use the first function?