1 / 20

Fundamentals of C++

Fundamentals of C++. Yingcai Xiao 09/03/08. Class Definition IO Template vector C Pointer Dynamic Memory Allocation. Outline. Example: How to define a class (user-defined data type). class Rectangle { protected: int width; int height; public: Rectangle () { }

adsila
Download Presentation

Fundamentals of C++

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Fundamentals of C++ Yingcai Xiao 09/03/08

  2. Class Definition • IO • Template • vector • C • Pointer • Dynamic Memory Allocation Outline

  3. Example: How to define a class (user-defined data type) class Rectangle { protected: int width; int height; public: Rectangle () { } Rectangle (int cx, int cy) {width = cx; height = cy;} int area() {return with*height;} };

  4. Class Name; In C++: “Rectangle rect” declares an object of class Rectangle. rect Instantiating a Class in C++ “rect” is the name of a memory space that stores a Rectangle object.

  5. Reading Input: cin • console input • an object of iostreams • only supports one operator >> • reads input for its arguments, one at a time • auto converts input to the type of the arguments • Displaying Output: cout • console output • an object of iostreams • only supports one operator << • sends output to the console for its arguments, one at a time • auto converts output of the type of the arguments for display • display format can be specified Console IO

  6. #include <string> #include <fstream> // file io streams #include <iostream> // file io streams using namespace std; int main() { string infile, outfile; cout << "Enter input file name: \n"; cin >> infile; cout << "Enter output file name: \n"; cin >> outfile; ifstream in(infile.data()); // Open for reading ofstream out(outfile.data()); // Open for writing string s; while(getline(in, s)) // Discards newline char out << s << "\n"; // ... must add it back } ///:~ File IO

  7. <T> x; Where type, T, is a variable too. T : int => int x; T : float => float x; Template (Type Variables)

  8. To use: #include <vector> To define: vector <type> v; To add an element: v.push_back(object); To access an element: v[i] (just like an array) Eaxmples: vector<int> vi; vector<string> vs; int i; string s; cin >> i >> s; vi.push_back(i); vs.push_back(s); cout << vi[0] << vs[0]; vector (smart array)

  9. Data storage types: • int, float, char, array (e.g., int ia[4];), enum, struct, union • No classes in C. • Computation operators: • Math: +, -, *, /, %, =, -=, +=, *=, /= • Logical: <, >, <=, >-, ==, !=, ||, &&, • bitwise: |, &, >>, <<,^ • Control statements: • if-else, while, do-while, for, switch, C in C++

  10. Pointers in C and C++

  11. Variable • A variable is a named memory space. • The memory space stores the value of the variable. • The size of the memory is determined by the variable’s type. • The limit of the variable is determined by the size of the memory and the type of the variable. Example: int i = 8; i(4 bytes of memory) 8 Variables in C and C++ • The memory of a variable is allocated at compile time. • The memory of an automatic variable is automatically freed at run time when the variable is no longer in used. • By default all variables are automatic. The following statements are the same: int i = 8; auto int i = 8;

  12. An array of memory can be allocated as • int ia[2]; • ia[0] = 1; • ia[1] = 2; • or • int ia[2] = {1,2}; • or • int ia[] = {1,2}; Arrays in C and C++ Example: int ia[2] = {1,2}; ia[0] ia[1] (4 bytes each) 1 2 • Array memories are “allocated” at compile time.

  13. & • Operator & returns the address of an variable • e.g.: &i, &ia[0], &ia[1] • The address of a memory is expressed as a hex number • e.g.: 0xffaabbcc Address of a Variables

  14. Pointer • A pointer is a named memory space. • The size of the memory is determined by the OS (32 bits, 64 bits, …), and it determines the maximum addressing space of the OS. • The memory space of a pointer stores the address of another memory space. We usually say, the pointer points to the memory space. • The size of the pointed memory space is determined by the type of the pointer. • A pointer is declared as • type * name; Pointers in C and C++ Example: int * ip; ip(4 bytes of memory for a 32bit OS) 0xffaabbcc int i = 8; ip = &i; i 8

  15. Memories can be allocated at run-time (dynamic memory allocation). • “new” is the operator for DMA. • It allocates a memory and returns its address (but gives it no name.) • A pointer is needed to store the address of a dynamically allocated memory. • The size of the memory is determined by the argument supplied to “new”. • Operator “*” dereference a pointer to access the memory it points to. • A pointer needs to point to a valid memory before being dereferenced. • A dereferenced pointer can be used just like a named memory (a regular variable). Dynamical Memory Allocation (DMA) int * ip; ip(4 bytes of memory for 32bit OS) 0xffaabbcc no name ip = new (int); 8 *ip = 8; cout << *ip;

  16. There are two ways to dereference a DMA object. • * • -> • Example: • Dog *dp; • dp = new Dog(“Stommy”); • cout << (*dp).getName(); • cout << dp->getName(); • Exam Pet.cpp Dereferencing a DMA object

  17. /* Pet.cpp. This program demonstrates OOP constructs in C++ Dr. Xiao (9/6/07), adopted from TIC++. */ #include <iostream> // head file for predefined io classes and objects #include <string> // head file for the predefined string class #include <vector>// head file for the predefined vector template using namespace std; class Pet { // define a class, group everything together, encapsulate as needed. protected: string name; // protected members can be accessed by child classes public: Pet() {name = “I have no name.";} // default constructor Pet(string nm){name = nm;} // constructor string getName() {return name;} // to be inherited by child classes //virtual method, to be overridden by child classes, for polymorphism virtual string speak() const { return “’I can't speak.’”; } }; Your second C++ Program

  18. class Dog : public Pet { // inheritance public: Dog(){name = “I am a dog without a name.";} Dog(string nm){name = nm;} string speak() const { return "'bark! bark!'"; } }; class Cat : public Pet { public: Cat(){name = " I am a cat without a name.";} Cat(string nm){name = nm;} string speak() const { return "'meow! meow!'"; } }; Your second C++ Program

  19. int main() { Dog d("Midnight"); Cat c("Ginger"); Pet p("Dummy"); cout << d.getName() << " says, " << d.speak() <<endl; cout << c.getName() << " says, " << c.speak() <<endl; cout << p.getName() << " says, " << p.speak() <<endl; cout << “We put all the pets together to make it easier to take care of them (code reuse). \n”; vector<Pet> pets; // “vector” mimics variable-size array, its type is a variable too (template) pets.push_back(d); pets.push_back(c); pets.push_back(p); for(int i=0; i<pets.size();i++) cout << "Pet " << i << " (" << pets[i].getName()<< ") " << " says " << pets[i].speak() << endl; cout << "The above did not work correctly. No one can speak now.\n”; cout << “Incorrect use of virtual methods for polymorphism. \n"; Your second C++ Program

  20. cout << "The following do work correctly. \n”; cout << “Correct use of a virtual methodfor polymorphism. \n"; vector<Pet *> pets2; // pointer type pets2.push_back(&d); // taking address of d pets2.push_back(&c); pets2.push_back(&p); for(int i=0; i<pets2.size();i++) cout << "Pet " << i << " (" << pets2[i]->getName()<< ") " << " says " << pets2[i]->speak() << endl; cout << “Correct use of a virtual method for polymorphism. \n"; vector<Pet *> pets3; pets3.push_back(new Dog("Midnight2")); // a new dog created at run time pets3.push_back(new Cat("Ginger2")); pets3.push_back(new Pet("Dummy2")); for(int i=0; i<pets3.size();i++) cout << "Pet " << i << " (" << pets3[i]->getName()<< ") " << " says " << pets3[i]->speak() << endl; cout << "Please enter 'q' to quit.\n ";char a; cin >> a; } Your second C++ Program

More Related