Вы находитесь на странице: 1из 20

Fundamentals of C++

Yingcai Xiao 09/03/08

Class Definition IO Template vector C Pointer Dynamic Memory Allocation

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;} };

Instantiating a Class in C++

Class Name; In C++: Rectangle rect declares an object of class Rectangle. rect

int width; int height;

Rectangle ()
Rectangle (int w, int h) Area()
rect is the name of a memory space that stores a Rectangle object.

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

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

Template (Type Variables)

<T> x; Where type, T, is a variable too. T : int => int x;

T : float => float x;

vector (smart array)

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];

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,

Pointers in C and C++

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 variables 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)

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;

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] 1

ia[1] (4 bytes each) 2

Array memories are allocated at compile time.

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

Pointers in C and C++

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

Dynamical Memory Allocation (DMA)

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

Dereferencing a DMA object

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

Your second C++ Program

/* 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

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

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

cout << "The following do work correctly. \n; cout << Correct use of a virtual method for 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; }