Presentation is loading. Please wait.

Presentation is loading. Please wait.

Fundamentals of C++ Yingcai Xiao 09/03/08. Outline Class Definition IO Template vector C Pointer Dynamic Memory Allocation.

Similar presentations


Presentation on theme: "Fundamentals of C++ Yingcai Xiao 09/03/08. Outline Class Definition IO Template vector C Pointer Dynamic Memory Allocation."— Presentation transcript:

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

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

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

4 Instantiating a Class in C++ Class Name; In C++: “Rectangle rect” declares an object of class Rectangle. int width; int height; Rectangle () Rectangle (int w, int h) Area() rect “rect” is the name of a memory space that stores a Rectangle object.

5 Console IO  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

6 File IO #include #include // 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 } ///:~

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

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

9 C in C++ 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,

10 Pointers in C and C++

11 Variables in C and C++ 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 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 Arrays in C and C++ 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}; Example: int ia[2] = {1,2}; ia[0] ia[1] (4 bytes each) 1 2 Array memories are “allocated” at compile time.

13 Address of a Variables & 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

14 Pointers in C and C++ int i = 8; ip = &i; i 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; 8 0xffaabbcc Example: int * ip; ip (4 bytes of memory for a 32bit OS)

15 Dynamical Memory Allocation (DMA) ip = new (int); no name 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). 0xffaabbcc int * ip; ip (4 bytes of memory for 32bit OS) *ip = 8; cout << *ip; 8

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

17 Your second C++ Program /* Pet.cpp. This program demonstrates OOP constructs in C++ Dr. Xiao (9/6/07), adopted from TIC++. */ #include // head file for predefined io classes and objects #include // head file for the predefined string class #include // 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.’”; } };

18 Your second C++ Program 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!'"; } };

19 Your second C++ Program 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 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";

20 Your second C++ Program cout << "The following do work correctly. \n”; cout << “Correct use of a virtual method for polymorphism. \n"; vector 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 getName()<< ") " speak() << endl; cout << “Correct use of a virtual method for polymorphism. \n"; vector 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 getName()<< ") " speak() << endl; cout > a; }


Download ppt "Fundamentals of C++ Yingcai Xiao 09/03/08. Outline Class Definition IO Template vector C Pointer Dynamic Memory Allocation."

Similar presentations


Ads by Google