C++ Mini-Course

Click here to load reader

download C++ Mini-Course

of 57

  • date post

  • Category


  • view

  • download


Embed Size (px)


C++ Mini-Course . C++ Rulez!. Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion. C++ Mini-Course Part 1: Mechanics. C++ is a superset of C. New Features include Classes (Object Oriented) - PowerPoint PPT Presentation

Transcript of C++ Mini-Course

  • C++ Mini-Course

    Part 1: MechanicsPart 2: BasicsPart 3: ReferencesPart 4: ConstPart 5: InheritancePart 6: LibrariesPart 7: Conclusion

    C++ Rulez!

  • C++ Mini-Course

    Part 1: Mechanics

  • C++ is a superset of CNew Features includeClasses (Object Oriented)Templates (Standard Template Library)Operator OverloadingSlightly cleaner memory operations

  • Some C++ code

  • #include Segment.h


    #includeInsert header file at this point.Use library header.

  • Header Guards#ifndef __SEGMENT_HEADER__#define __SEGMENT_HEADER__

    // contents of Segment.h//...


    To ensure it is safe to include a file more than once.

  • Header Guards#ifndef __SEGMENT_HEADER__#define __SEGMENT_HEADER__

    // contents of segment.H//...


    To ensure it is safe to include a file more than once.If this variable is not definedDefine it.End of guarded area.

  • Circular IncludesWhats wrong with this picture?

    How do we fix it?

  • Forward DeclarationsIn header files, only include what you must.

    If only pointers to a class are used, use forward declarations.

  • CompilationObject filesExecutableExternal Libraries, libc.so, libcs123.so

  • OK, OK. How do I run my Program?

    > make

    And if all goes well> ./myprog

  • C++ Mini-Course

    Part 2: Basics

  • What is a pointer?int x = 10;int *p;

    p = &x;

    p gets the address of x in memory.px10

  • What is a pointer?int x = 10;int *p;

    p = &x;

    *p = 20;

    *p is the value at the address p.px20

  • What is a pointer?int x = 10;int *p = NULL;

    p = &x;

    *p = 20;

    Declares a pointer to an integer& is address operator gets address of x * dereference operator gets value at p

  • Allocating memory using newPoint *p = new Point(5, 5);

    new can be thought of a function with slightly strange syntaxnew allocates space to hold the object.new calls the objects constructor.new returns a pointer to that object.

  • Deallocating memory using delete // allocate memoryPoint *p = new Point(5, 5);

    ...// free the memorydelete p;

    For every call to new, there must beexactly one call to delete.

  • Using new with arraysint x = 10;int* nums1 = new int[10]; // okint* nums2 = new int[x]; // ok

    Initializes an array of 10 integers on the heap.C++ equivalent of the following C codeint* nums = (int*)malloc(x * sizeof(int));

  • Using new with multidimensional arraysint x = 3, y = 4;int** nums3 = new int[x][4];// okint** nums4 = new int[x][y];// BAD!

    Initializes a multidimensional arrayOnly the first dimension can be a variable. The rest must be constants.Use single dimension arrays to fake multidimensional ones

  • Using delete on arrays// allocate memoryint* nums1 = new int[10];int* nums3 = new int[x][4][5];

    ...// free the memorydelete[] nums1;delete[] nums3;

    Have to use delete[].

  • Destructors

    delete calls the objects destructor.delete frees space occupied by the object.

    A destructor cleans up after the object.Releases resources such as memory.

  • Destructors an Exampleclass Segment{public: Segment(); virtual ~Segment();private: Point *m_p0, *m_p1;};

  • Destructors an ExampleSegment::Segment(){ m_p0 = new Point(0, 0); m_p1 = new Point(1, 1);}Segment::~Segment(){ if (m_p0) delete m_p0; if (m_p1) delete m_p1;}

  • New vs Malloc Never mix new/delete with malloc/free

    MallocNewStandard C FunctionOperator (like ==, +=, etc.)Used sparingly in C++; used frequently in COnly in C++Used for allocating chunks of memory of a given size without respect to what will be stored in that memoryUsed to allocate instances of classes / structs / arrays and will invoke an objects constructorReturns void* and requires explicit castingReturns the proper typeReturns NULL when there is not enough memoryThrows an exception when there is not enough memoryEvery malloc() should be matched with a free()Every new/new[] should be matched with a delete/delete[]

  • Classes vs StructsDefault access specifier for classes is private; for structs it is publicExcept for this difference, structs are functionally the same as classes, but the two are typically used differently: structs should be thought of as lightweight classes that contain mostly data and possibly convenience methods to manipulate that data and are hardly ever used polymorphicallystruct Point { int x; int y; // convenience constructor Point(int a, int b) : x(a), y(b) { } // @returns distance to another point double distance(const Point &pnt) { int dx = m_x pnt.x; int dy = m_y pnt.y; return math.sqrt(dx*dx + dy*dy); }};class Segment { public: Segment(); virtual ~Segment(); void setPoints(int x0, int y0, int x1, int y1); protected: Point *m_p0, *m_p1;};

    void Segment::setPoints(int x0, int y0, int x1, int y1) { m_p0 = new Point(x0, y0); m_p1 = new Point(x1, y1);}

  • Syntactic Sugar ->Point *p = new Point(5, 5);

    // Access a member function:(*p).move(10, 10);

    // Or more simply:p->move(10, 10);

  • Stack vs. HeapWhat happens when p goes out of scope?

    On the Heap / Dynamic allocation On the Stack / Automatic allocationdrawStuff() { Point *p = new Point(); p->move(10,10); //...}drawStuff() { Point p(); p.move(5,5); //...}

  • Summary with Header Filebegin header guardheader fileforward declarationclass declarationconstructordestructorend header guardmember variablesneed semi-colon

  • C++ Mini-Course

    Part 3: References

  • Passing by valuevoid Math::square(int i) { i = i*i;}

    int main() { int i = 5; Math::square(i); cout

  • Passing by referencevoid Math::square(int &i) { i = i*i;}

    int main() { int i = 5; Math::square(i); cout

  • What is a reference?An alias another name for an object. int x = 5; int &y = x; // y is a // reference to x y = 10;

    What happened to x?What happened to y?

  • What is a reference?An alias another name for an object. int x = 5; int &y = x; // y is a // reference to x y = 10;

    What happened to x?What happened to y? y is x.

  • Why are they useful?Unless you know what you are doing, do not pass objects by value; either use a pointer or a reference.Some people find it easier to deal with references rather then pointers, but in the end there is really only a syntactic difference (neither of them pass by value).Can be used to return more than one value (pass multiple parameters by reference)

  • How are references different from Pointers?

    Reference Pointer int &a; int *a; int a = 10; int b = 20; int &c = a; c = b; int a = 10; int b = 20; int *c = &a; c = &b;

  • C++ Mini-Course

    Part 4: const

  • Introducing: constvoid Math::printSquare(const int &i){ i = i*i; cout
  • Can also pass pointers to constvoid Math::printSquare(const int *pi) { *pi = (*pi) * (*pi); cout
  • Declaring things const

    const River nile;

    const River* nilePc;

    River* const nileCp;

    const River* const nileCpc

  • Read pointer declarations right to left// A const Riverconst River nile;

    // A pointer to a const Riverconst River* nilePc;

    // A const pointer to a RiverRiver* const nileCp;

    // A const pointer to a const Riverconst River* const nileCpc

  • Lets Try ReferencesRiver nile;

    const River &nileC = nile;

    // Will this work?River &nile1 = nileC;

  • How does const work here?void Math::printSquares(const int &j, int &k) { k = k*k; // Does this compile? cout
  • Returning const references is OKclass Point { public: const double &getX() const; const double &getY() const; void move(double dx, double dy); protected: double m_x, m_y;};const double & Point::getX() const { return m_x;}Function wont change *this.

  • C++ Mini-Course

    Part 5: Inheritance

  • How does inheritance work?#include Segment.hclass DottedSegment : public Segment{// DottedSegment declaration};

    must include parent header fileDottedSegment publicly inherits from Segment

  • virtualIn Java every method invocation is dynamically bound, meaning for every method invocation the program checks if a sub-class has overridden the method. You can disable this (somewhat) by using the keyword final in JavaIn C++ you have to declare the method virtual if you want this functionality. (So, virtual is the same thing as not final)Just like you rarely say things are final in Java, you should rarely not say things are virtual in C++

  • pure virtual functionsIn Java, the abstract keyword means the function is undefined in the superclass.In C++, we use pure virtual functions:virtual int mustRedfineMe(char *str) = 0;This function must be implemented in a subclass.

  • Resolving functionsIn Java:

    // Overriding methodspublic void overloaded(){ println(woohoo); super.overloaded();}

    //constructorpublic Subclass(){super();}In C++:

    // Overriding methodsvoid Subclass::overloaded(){ cout

  • virtualBasic advice: for now make every method virtual except the constructorMake you declare your destructors virtual; if you do not declare a destructor a non-virtual one will be defined for you Segment(); virtual ~Segment();this is important