SlideShare a Scribd company logo
Brought to you by
www.facebook.com/rohithiphopper
   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>           Includes function definitions
using namespace std;           for
                               console input and output.
float c(float x) {
   return x*x*x;              Function declaration.
}                             Function definition.

int main() {
   float x;                   Program starts here.
   cin >> x;                  Local variable declaration.
   cout << c(x) << endl;
                              Console input.
    return 0;                 Console output.
}                             Exit main function.
C++ tutorial
// This is main.cc             // This is mymath.h
#include <iostream>            #ifndef MYMATH
#include “mymath.h”            #define MYMATH
using namespace std;
                               float c(float x);
int main() {                   float d(float x);
   // ...stuff...
}                              #endif



    Functions are declared in m at h. h, but not defined.
                               ym
      They are implemented separately in m at h. c c .
                                          ym
main.cc              mymath.cc             mydraw.cc

      ↓                     ↓                     ↓
g++ -c main.cc       g++ -c mymath.cc     g++ -c mydraw.cc

      ↓                     ↓                     ↓
    main.o               mymath.o             mydraw.o

      ↓                     ↓                     ↓
     g++ -o myprogram main.o mathstuff.o drawstuff.o

      ↓
  myprogram      →
// This is main.cc
#include <GL/glut.h>                  Include OpenGL functions.
#include <iostream>                   Include standard IO
using namespace std;                   functions.
                                      Long and tedious
int main() {                           explanation.
   cout << “Hello!” << endl;
   glVertex3d(1,2,3);
   return 0;                          Calls function from standard
}                                      IO.
                                      Calls function from OpenGL.




% g++ -c main.cc                      Make object file.
                                      Make executable, link GLUT.
% g++ -o myprogram –lglut main.o      Execute program.
% ./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.
Most assignments include
INCFLAGS = 
       -
       I/afs/csail/group/graphics/courses/6.837/public/includ

                                                                makef i l es , which describe
       e
LINKFLAGS = 
       -L/afs/csail/group/graphics/courses/6.837/public/lib 

CFLAGS
       -lglut -lvl
          = -g -Wall -ansi
                                                                the files, dependencies, and
CC
SRCS
          = g++
          = main.cc parse.cc curve.cc surf.cc camera.cc            steps for compilation.
OBJS      = $(SRCS:.cc=.o)
PROG      = a1



                                                                  You can just type m
all: $(SRCS) $(PROG)

$(PROG): $(OBJS)
                                                                                     ake.
        $(CC) $(CFLAGS) $(OBJS) -o $@ $(LINKFLAGS)

.cc.o:

                                                                So you don’t have to know
          $(CC) $(CFLAGS) $< -c -o $@ $(INCFLAGS)



                                                                the stuff from the past few
depend:
          makedepend $(INCFLAGS) -Y $(SRCS)

clean:
          rm $(OBJS) $(PROG)                                                slides.
main.o: parse.h curve.h tuple.h



                                                                   But it’s nice to know.
# ... LOTS MORE ...
C++ tutorial
#include <iostream>
using namespace std;

int main() {                  Arrays must have known
   int n;
                               sizes at compile time.
   cin >> n;
   float f[n];
                               This doesn’t compile.
    for (int i=0; i<n; i++)
       f[i] = i;

    return 0;
}
#include <iostream>
                              Allocate the array during
using namespace std;
                                 runtime using new.
int main() {
   int n;
   cin >> n;                  No garbage collection, so
   float *f = new float[n];    you have to delete.
    for (int i=0; i<n; i++)
       f[i] = i;                Dynamic memory is
                               useful when you don’t
    delete [] f;
    return 0;                  know how much space
}                                    you need.
#include <iostream>
                              STL vector is a resizable
#include <vector>
using namespace std;           array with all dynamic
                              memory handled for you.
int main() {
   int n;
   cin >> n;                   STL has other cool stuff,
   vector<float> f(n);         such as strings and sets.
    for (int i=0; i<n; i++)
       f[i] = i;
                               If you can, use the STL
    return 0;                    and avoid dynamic
}                                     memory.
#include <iostream>
#include <vector>
using namespace std;           An alternative method
                              that does the same thing.
int main() {
   int n;
   cin >> n;                   Methods are called with
   vector<float> f;
                              the dot operator (same as
    for (int i=0; i<n; i++)             Java).
       f.push_back(i);

    return 0;                 vector is poorly named,
}                             it’s actually just an array.
float twice1(float x) {    This works as expected.
   return 2*x;
}

void twice2(float x) {
   x = 2*x;
                           This does nothing.
}

int main() {
   float x = 3;
   twice2(x);
   cout << x << endl;      The variable is
   return 0;                 unchanged.
}
vector<float>
twice(vector<float> x) {
   int n = x.size();           There is an incredible
   for (int i=0; i<n; i++)   amount of overhead here.
      x[i] = 2*x[i];
   return x;
}
                             This copies a huge array
int main() {                  two times. It’s stupid.
   vector<float>
   y(9000000);
   y = twice(y);              Maybe the compiler’s
   return 0;                 smart. Maybe not. Why
}
                                     risk it?
void twice3(float *x) {    Pass pointer by value
   (*x) = 2*(*x);
                             and
}
                             access data using
void twice4(float &x) {      asterisk.
   x = 2*x;
}
                           Pass by reference.
int main() {
   float x = 3;
   twice3(&x);
   twice4(x);
   return 0;
}                          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.
C++ tutorial
   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

More Related Content

PPT
C++totural file
PDF
All I know about rsc.io/c2go
PDF
Javascript & Ajax Basics
PDF
ECSE 221 - Introduction to Computer Engineering - Tutorial 1 - Muhammad Ehtas...
PPTX
Hacking Go Compiler Internals / GoCon 2014 Autumn
PDF
JavaScript ES6
KEY
Objective-Cひとめぐり
PDF
An Intro To ES6
C++totural file
All I know about rsc.io/c2go
Javascript & Ajax Basics
ECSE 221 - Introduction to Computer Engineering - Tutorial 1 - Muhammad Ehtas...
Hacking Go Compiler Internals / GoCon 2014 Autumn
JavaScript ES6
Objective-Cひとめぐり
An Intro To ES6

What's hot (20)

PDF
ES6 - Next Generation Javascript
PDF
Imugi: Compiler made with Python
PDF
MP in Clojure
PDF
Free Monads Getting Started
PDF
NativeBoost
PDF
Explaining ES6: JavaScript History and What is to Come
PPT
iOS Development with Blocks
PDF
The best of AltJava is Xtend
PDF
Objective-C Blocks and Grand Central Dispatch
DOCX
Arrry structure Stacks in data structure
PDF
Swiftの関数型っぽい部分
PDF
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
PDF
ECMAScript 6
PDF
JavaScript - new features in ECMAScript 6
PDF
Building fast interpreters in Rust
PDF
Bind me if you can
DOC
Study of aloha protocol using ns2 network java proram
ODP
EcmaScript 6
PDF
Python opcodes
PPT
Constructor,destructors cpp
ES6 - Next Generation Javascript
Imugi: Compiler made with Python
MP in Clojure
Free Monads Getting Started
NativeBoost
Explaining ES6: JavaScript History and What is to Come
iOS Development with Blocks
The best of AltJava is Xtend
Objective-C Blocks and Grand Central Dispatch
Arrry structure Stacks in data structure
Swiftの関数型っぽい部分
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
ECMAScript 6
JavaScript - new features in ECMAScript 6
Building fast interpreters in Rust
Bind me if you can
Study of aloha protocol using ns2 network java proram
EcmaScript 6
Python opcodes
Constructor,destructors cpp
Ad

Viewers also liked (20)

PPT
C++ tutorials
PDF
Oop c++ tutorial
PPT
C++ classes tutorials
PPT
Tutorial csharp
PPT
C++ classes tutorials
PPTX
Python in big data world
PDF
C++ TUTORIAL 8
PPTX
Python programming - Everyday(ish) Examples
PDF
C++ TUTORIAL 1
PPTX
C++ Tutorial
PPTX
Why Learn PHP Programming?
PPTX
C++ classes
DOC
Php tutorial
PPT
C++ Inheritance
PPTX
Tutorial classes meeting and workshop november 17th 2015
PPTX
C# Tutorial
PPT
Beginners PHP Tutorial
PDF
Ms1 test 1 second term 2016 2017
PPTX
Oop c++class(final).ppt
PPTX
C Programming Language Tutorial for beginners - JavaTpoint
C++ tutorials
Oop c++ tutorial
C++ classes tutorials
Tutorial csharp
C++ classes tutorials
Python in big data world
C++ TUTORIAL 8
Python programming - Everyday(ish) Examples
C++ TUTORIAL 1
C++ Tutorial
Why Learn PHP Programming?
C++ classes
Php tutorial
C++ Inheritance
Tutorial classes meeting and workshop november 17th 2015
C# Tutorial
Beginners PHP Tutorial
Ms1 test 1 second term 2016 2017
Oop c++class(final).ppt
C Programming Language Tutorial for beginners - JavaTpoint
Ad

Similar to C++ tutorial (20)

PPT
CppTutorial.ppt
PPT
Cpp tutorial
PDF
C++primer
PPTX
Intro to C++
PPTX
C++ language
PDF
Cpprm
PDF
C++ L01-Variables
PPT
PDF
Ds lab handouts
PDF
CBSE Question Paper Computer Science with C++ 2011
PDF
lec02 .pdf
PPTX
Cs1123 3 c++ overview
PDF
02 c++g3 d
PPTX
Cs1123 11 pointers
PPT
Lecture#6 functions in c++
PDF
C++ Chapter I
DOC
Oops lab manual2
PPT
02 functions, variables, basic input and output of c++
PDF
CppQuickRef.pdf
PDF
C++ QUICK REFERENCE.pdf
CppTutorial.ppt
Cpp tutorial
C++primer
Intro to C++
C++ language
Cpprm
C++ L01-Variables
Ds lab handouts
CBSE Question Paper Computer Science with C++ 2011
lec02 .pdf
Cs1123 3 c++ overview
02 c++g3 d
Cs1123 11 pointers
Lecture#6 functions in c++
C++ Chapter I
Oops lab manual2
02 functions, variables, basic input and output of c++
CppQuickRef.pdf
C++ QUICK REFERENCE.pdf

Recently uploaded (20)

PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
Classroom Observation Tools for Teachers
PDF
Pre independence Education in Inndia.pdf
PPTX
Pharma ospi slides which help in ospi learning
PDF
Basic Mud Logging Guide for educational purpose
PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
O5-L3 Freight Transport Ops (International) V1.pdf
Pharmacology of Heart Failure /Pharmacotherapy of CHF
human mycosis Human fungal infections are called human mycosis..pptx
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
2.FourierTransform-ShortQuestionswithAnswers.pdf
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Microbial disease of the cardiovascular and lymphatic systems
Classroom Observation Tools for Teachers
Pre independence Education in Inndia.pdf
Pharma ospi slides which help in ospi learning
Basic Mud Logging Guide for educational purpose
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
FourierSeries-QuestionsWithAnswers(Part-A).pdf
O7-L3 Supply Chain Operations - ICLT Program
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...

C++ tutorial

  • 1. Brought to you by www.facebook.com/rohithiphopper
  • 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>  Includes function definitions using namespace std; for console input and output. float c(float x) { return x*x*x;  Function declaration. }  Function definition. int main() { float x;  Program starts here. cin >> x;  Local variable declaration. cout << c(x) << endl;  Console input. return 0;  Console output. }  Exit main function.
  • 6. // This is main.cc // This is mymath.h #include <iostream> #ifndef MYMATH #include “mymath.h” #define MYMATH using namespace std; float c(float x); int main() { float d(float x); // ...stuff... } #endif Functions are declared in m at h. h, but not defined. ym They are implemented separately in m at h. c c . ym
  • 7. main.cc mymath.cc mydraw.cc ↓ ↓ ↓ g++ -c main.cc g++ -c mymath.cc g++ -c mydraw.cc ↓ ↓ ↓ main.o mymath.o mydraw.o ↓ ↓ ↓ g++ -o myprogram main.o mathstuff.o drawstuff.o ↓ myprogram →
  • 8. // This is main.cc #include <GL/glut.h>  Include OpenGL functions. #include <iostream>  Include standard IO using namespace std; functions.  Long and tedious int main() { explanation. cout << “Hello!” << endl; glVertex3d(1,2,3); return 0;  Calls function from standard } IO.  Calls function from OpenGL. % g++ -c main.cc  Make object file.  Make executable, link GLUT. % g++ -o myprogram –lglut main.o  Execute program. % ./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. Most assignments include INCFLAGS = - I/afs/csail/group/graphics/courses/6.837/public/includ makef i l es , which describe e LINKFLAGS = -L/afs/csail/group/graphics/courses/6.837/public/lib CFLAGS -lglut -lvl = -g -Wall -ansi the files, dependencies, and CC SRCS = g++ = main.cc parse.cc curve.cc surf.cc camera.cc steps for compilation. OBJS = $(SRCS:.cc=.o) PROG = a1 You can just type m all: $(SRCS) $(PROG) $(PROG): $(OBJS) ake. $(CC) $(CFLAGS) $(OBJS) -o $@ $(LINKFLAGS) .cc.o: So you don’t have to know $(CC) $(CFLAGS) $< -c -o $@ $(INCFLAGS) the stuff from the past few depend: makedepend $(INCFLAGS) -Y $(SRCS) clean: rm $(OBJS) $(PROG) slides. main.o: parse.h curve.h tuple.h But it’s nice to know. # ... LOTS MORE ...
  • 12. #include <iostream> using namespace std; int main() { Arrays must have known int n; sizes at compile time. cin >> n; float f[n]; This doesn’t compile. for (int i=0; i<n; i++) f[i] = i; return 0; }
  • 13. #include <iostream> Allocate the array during using namespace std; runtime using new. int main() { int n; cin >> n; No garbage collection, so float *f = new float[n]; you have to delete. for (int i=0; i<n; i++) f[i] = i; Dynamic memory is useful when you don’t delete [] f; return 0; know how much space } you need.
  • 14. #include <iostream> STL vector is a resizable #include <vector> using namespace std; array with all dynamic memory handled for you. int main() { int n; cin >> n; STL has other cool stuff, vector<float> f(n); such as strings and sets. for (int i=0; i<n; i++) f[i] = i; If you can, use the STL return 0; and avoid dynamic } memory.
  • 15. #include <iostream> #include <vector> using namespace std; An alternative method that does the same thing. int main() { int n; cin >> n; Methods are called with vector<float> f; the dot operator (same as for (int i=0; i<n; i++) Java). f.push_back(i); return 0; vector is poorly named, } it’s actually just an array.
  • 16. float twice1(float x) {  This works as expected. return 2*x; } void twice2(float x) { x = 2*x;  This does nothing. } int main() { float x = 3; twice2(x); cout << x << endl;  The variable is return 0; unchanged. }
  • 17. vector<float> twice(vector<float> x) { int n = x.size(); There is an incredible for (int i=0; i<n; i++) amount of overhead here. x[i] = 2*x[i]; return x; } This copies a huge array int main() { two times. It’s stupid. vector<float> y(9000000); y = twice(y); Maybe the compiler’s return 0; smart. Maybe not. Why } risk it?
  • 18. void twice3(float *x) {  Pass pointer by value (*x) = 2*(*x); and } access data using void twice4(float &x) { asterisk. x = 2*x; }  Pass by reference. int main() { float x = 3; twice3(&x); twice4(x); return 0; }  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.
  • 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

Editor's Notes

  • #5: 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
  • #7: 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.
  • #8: 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
  • #9: 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
  • #13: why? examples of purely functional programming languages… haskell, basic scheme…
  • #14: why? examples of purely functional programming languages… haskell, basic scheme…
  • #15: why? examples of purely functional programming languages… haskell, basic scheme…
  • #16: why? examples of purely functional programming languages… haskell, basic scheme…
  • #17: So why don’t we just use the first function?
  • #18: So why don’t we just use the first function?
  • #19: So why don’t we just use the first function?