introduction to c++ - duke computer science+.pdf · c++ • data > characteristics • functions...

32
Introduction to C++ Ionut Constandache

Upload: others

Post on 25-Jun-2020

10 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to C++ - Duke Computer Science+.pdf · C++ • Data > characteristics • Functions > behavior • Implement all of them in the same “structure” if they belong together

Introduction to C++

Ionut Constandache

Page 2: Introduction to C++ - Duke Computer Science+.pdf · C++ • Data > characteristics • Functions > behavior • Implement all of them in the same “structure” if they belong together

Data Types (from C)data­type   # bytes(typical)        valuesint                 4         ­2,147,483,648 to 2,147,483,647       char                1         ­128 to 127          float               4        3.4E+/­38 (7 digits)                       double              8        1.7E+/­308 (15 digits long)               long                4       ­2,147,483,648 to 2,147,483,647     short               2        ­32,768 to 32,767 • Others (look them up): 

• signed / unsigned  ­ int, char, long, short• long double

• ex: int num=12000;

  int array[100]; 

Page 3: Introduction to C++ - Duke Computer Science+.pdf · C++ • Data > characteristics • Functions > behavior • Implement all of them in the same “structure” if they belong together

Like Java, like C, like C++• Operators same as Java: 

• Arithmetic• int i = i+1; i++; i­­; i *= 2;• +, ­, *, /, %,

• Relational and Logical• <, >, <=, >=, ==, !=• &&, ||, &, |, !

• Syntax same as in Java:• if ( ) { } else { }• while ( ) { }• do { } while ( );• for(i=1; i <= 100; i++) { }• switch ( ) {case 1: … }• continue; break;

Page 4: Introduction to C++ - Duke Computer Science+.pdf · C++ • Data > characteristics • Functions > behavior • Implement all of them in the same “structure” if they belong together

struct birthday{    int month;    int day;    int year;  };

main() {  struct birthday mybday; /* ­ no ‘new’ needed ! */  /* then, it’s just like Java ! */  mybday.day=1; mybday.month=1; mybday.year=1977;}

struct (also from C)• Equivalent of Java’s classes with only 

data (no methods)

Page 5: Introduction to C++ - Duke Computer Science+.pdf · C++ • Data > characteristics • Functions > behavior • Implement all of them in the same “structure” if they belong together

C++• Data ­> characteristics • Functions ­> behavior

• Implement all of them in the same “structure” if they belong together– Functions tell what the user can do on data (also what they can 

not)

– The user should know only the interface (functions, some data members) but be hidden from the details of the implementation

– Change the mechanisms inside the “structure” without modifying the interface; user programs using the interface will not be disrupted

Page 6: Introduction to C++ - Duke Computer Science+.pdf · C++ • Data > characteristics • Functions > behavior • Implement all of them in the same “structure” if they belong together

class  • Class = the way of grouping data (characteristics) and functions (behaviors) together 

in C++

class Test{    private: // no one can access these members except the class creator  

int a,b;    public:  // all member declarations that follow can be used by anyone

int getA();void setA(int aa);

                 ………}; 

int Test::getA(){ return a;}void Test::setA(int aa){a = aa;} // setA can access the private data because it is a member of the class

int main(){   Test t;    t.setA(4);    int val = t.getA(); }

Page 7: Introduction to C++ - Duke Computer Science+.pdf · C++ • Data > characteristics • Functions > behavior • Implement all of them in the same “structure” if they belong together

Class constructor & destructor• Constructor destructor used to initialize the created objects• If a class has a constructor the compiler automatically calls the 

constructor at the point an object is created• The destructor is called when the object goes out of scope

class Test{   int a;   public:

  Test(int aa){ a = aa;}       ~Test();};void main(){    Test  t(10);    Test  array[3] = {Test(0), Test(1), Test(2)};      … // the destructor is called at the end of the scope in which the             // object was created}

Page 8: Introduction to C++ - Duke Computer Science+.pdf · C++ • Data > characteristics • Functions > behavior • Implement all of them in the same “structure” if they belong together

Default constructor• Default constructor = has no arguments, is automatically called if 

data is created and not initialized using another constructorclass Test{   int a;   public:

  Test() {a = 0;}  Test(int aa) { a = aa;}

        ~Test();  };

void main(){    Test  t;  // the data member a is initialized to 0     Test t1(10);  // the data member a is initialized to 10     Test  array[3]; // array[0], array[1], array[2] all have their private data                             // member a set to 0 }

Page 9: Introduction to C++ - Duke Computer Science+.pdf · C++ • Data > characteristics • Functions > behavior • Implement all of them in the same “structure” if they belong together

Pointers made easy ­ 1• Pointer = variable containing address of another variable

   int a;        /* data variable */   int *pa;  /* pointer variable */

   pa = &a; // & = address operator             // gets the address of variable a 

? ?

a pa

4300 4304

?

any int

any address

? 4300

a pa

4300 4304

Page 10: Introduction to C++ - Duke Computer Science+.pdf · C++ • Data > characteristics • Functions > behavior • Implement all of them in the same “structure” if they belong together

Pointers made easy ­ 2   *pa = 3;    /* indirection operator */

        int g=*pa; /* indirection:g is now 3 */

    a = 1;

a pa

4300 4304

3 4300

a pa

4300 4304

1 4300

Page 11: Introduction to C++ - Duke Computer Science+.pdf · C++ • Data > characteristics • Functions > behavior • Implement all of them in the same “structure” if they belong together

void main(void) {int j;int *ptr;

ptr=&j;   /* initialize ptr before using it */    /* *ptr=4 does NOT initialize ptr */

*ptr=4;     /* j <­ 4 */

j=*ptr;     /* j <­ ??? */}

Pointer Example

Page 12: Introduction to C++ - Duke Computer Science+.pdf · C++ • Data > characteristics • Functions > behavior • Implement all of them in the same “structure” if they belong together

Why use pointers?

void func(int a){ a = 10;} 

main(){    int b = 1;    func(b);   // b value is 1}

void func(int* pa){ *pa = 10;}

main() {  int b = 1;   func(&b);   // or int* pb; pb = &b; func(pb);  // b value is 10 }

•Modify data outside the scope they were created in

Page 13: Introduction to C++ - Duke Computer Science+.pdf · C++ • Data > characteristics • Functions > behavior • Implement all of them in the same “structure” if they belong together

Pointer to function

• Advantage ? more flexibility

 int func(); /*function returning integer*/ int *func(); /*function returning pointer to integer*/ int (*func)(); /*pointer to function returning integer*/ int *(*func)(); /*pointer to func returning ptr to int*/ 

Page 14: Introduction to C++ - Duke Computer Science+.pdf · C++ • Data > characteristics • Functions > behavior • Implement all of them in the same “structure” if they belong together

Passing  and returning arrays

void init_array(int* array, int size) {   /* why size ? */  /* arrays ALWAYS passed by reference */ int i; for (i = 0; i < size; i++)     array[i] = 0;  }

main() {  int list[5];  init_array(list, 5);}

Page 15: Introduction to C++ - Duke Computer Science+.pdf · C++ • Data > characteristics • Functions > behavior • Implement all of them in the same “structure” if they belong together

this• this = points to the current object

class Test{   int a;   public:

  Test() {a = 0};  Test(int a) {this­>a = a;}

        ~Test();  // no arguments for our example       int add(int b)       {           a = a + b;          // or this­>a = this­>a + b;       }       int setA(int b)       {          this­>a = b;       }};

Page 16: Introduction to C++ - Duke Computer Science+.pdf · C++ • Data > characteristics • Functions > behavior • Implement all of them in the same “structure” if they belong together

Referencesvoid func(int& a) // pass the                                    // address to func{  a = 10; } 

main(){  int b = 1;  func(b);  // b value is 10}

main(){  int a = 0;  int& refa = a;  refa++; // a will be 1 }

When declaring references they must be initialized

The reference is like a pointer which is dereferenced automatically 

The references can not be changed to reference another object

Page 17: Introduction to C++ - Duke Computer Science+.pdf · C++ • Data > characteristics • Functions > behavior • Implement all of them in the same “structure” if they belong together

Why references?• Cleaner than using pointers? Yes! but …• Copy Constructor = used to pass and return 

user defined types by value– Prevent the compiler from doing a bit copy– Define your own constructor to be used by the 

compiler when it needs to make a new object from an existing object

• The copy constructor has 1 parameter, a reference to an object from which you will build your new object

Page 18: Introduction to C++ - Duke Computer Science+.pdf · C++ • Data > characteristics • Functions > behavior • Implement all of them in the same “structure” if they belong together

Copy Constructorclass Test{   int a;   public:

  Test() {a = 0};  Test(int aa) { a = aa;}

       Test(const Test& b) { a = b.a; };        ~Test();        void incTest() {a++;}};

void nextTest(Test tt) // copy by value{  …..} 

main(){ Test t(10); Test t1 = t; nextTest(t);}

class X{  Y y;   public:      X(const X& x)      {        // y is object, may contain            // pointers to memory           // Do we want bit by bit          // copy of these pointers or the       // data they are pointing to?      } }

Page 19: Introduction to C++ - Duke Computer Science+.pdf · C++ • Data > characteristics • Functions > behavior • Implement all of them in the same “structure” if they belong together

Memory layout of programsHeader info

Code

Data ­ Heap

      0

  100

  400

  560

1010

1200

Dynamic memory

Local memory+ function callstack

all normal vars

new/delete

Data ­ stack

Page 20: Introduction to C++ - Duke Computer Science+.pdf · C++ • Data > characteristics • Functions > behavior • Implement all of them in the same “structure” if they belong together

new/delete• Dynamic memory allocation – allocate memory from heap at runtime

• Why at runtime? You may not know how many objects/variables you need until runtime

new = allocates memory on heap for the object and calls the constructor for that object

– Returns a pointer to that memory

Test* t = new Test(1);Test* arrayt = new Test[100]; // allocates storage on the heap for 100 Test 

objects and calls the constructor for each one

delete = calls the destructor for the object and releases the memory allocated to it on the heap

delete t;delete[ ] arrayt;

   

Page 21: Introduction to C++ - Duke Computer Science+.pdf · C++ • Data > characteristics • Functions > behavior • Implement all of them in the same “structure” if they belong together

Composition• Composition = put into your class other objects of other class types

class X {…};

class Y{         int i;         X obj;    public:

    int f();   // may use the functionality provided by X         int g();  // for example a vector class may be used to hold some                         // objects  } 

Page 22: Introduction to C++ - Duke Computer Science+.pdf · C++ • Data > characteristics • Functions > behavior • Implement all of them in the same “structure” if they belong together

Inheritance• Inheritance = create a class from an existing class to which you add extra 

functionality (data &| function members) without modifying the initial classclass Y : public X, Z, T{  // your own data members  // your own functions   …}

• Automatically get all the data members and member functions in the base class

• Add the word public, without it everything defaults to private• private data available in X,Z,T is not accessible in Y• If you want data other than that declared public in X to be accessible in a 

class that inherits X that data must be declared protected

Page 23: Introduction to C++ - Duke Computer Science+.pdf · C++ • Data > characteristics • Functions > behavior • Implement all of them in the same “structure” if they belong together

Inheritance (cont’)class Y : public X, Z, T{  // your own data members  // your own functions   h()   …}

If X has member functions f,g,h

main(){ Y y; y.f(); // calls the function defined in X y.g(); // calls the function defined in X y.h(); // calls the function defined in Y y.X::h(); // calls function defined in X}

Constructor initializer list = call constructors of classes being inherited to initialize the state (data members) inherited

The constructor for Y should be

Y::Y(new data members added): X(initializes data inherited from X),Z(initializes data inherited from Z),T(initializes data inherited from T)

    {       … // Y constructor    }

 

Page 24: Introduction to C++ - Duke Computer Science+.pdf · C++ • Data > characteristics • Functions > behavior • Implement all of them in the same “structure” if they belong together

virtual – Who is who?class Y : public X, Z, T{  // your own data members  // your own functions  void h();   // h is redefined in Y                  // h is also defined in X }

void func(X& x){x.h()}

main(){    Y y;    func(y); // who should be called function h() in X or function h() in Y?}

Page 25: Introduction to C++ - Duke Computer Science+.pdf · C++ • Data > characteristics • Functions > behavior • Implement all of them in the same “structure” if they belong together

virtual – Who is who? (cont’)

Early binding vs Late binding

In order to allow late binding (binding occurs at runtime ­ not done by the compiler) declare the function virtual in the base class (the one from which we inherit – in our example class X)  

Page 26: Introduction to C++ - Duke Computer Science+.pdf · C++ • Data > characteristics • Functions > behavior • Implement all of them in the same “structure” if they belong together

extern & staticextern int global; // global is declared in                            // another file

void func(){  static int a = 0;  a++;} 

static inside a function– the variable is initialized only once and is unavailable outside the 

function body– It remembers the value of a from one call to another

static void func() { … }

func is unavailable outside its scopeThe name is unavailable outside this file 

Page 27: Introduction to C++ - Duke Computer Science+.pdf · C++ • Data > characteristics • Functions > behavior • Implement all of them in the same “structure” if they belong together

An example#include <iostream>#include <string>#include <fstream>#include <cassert>#include <vector>

using namespace std;

class Reader{  vector<string> lines;  int no_lines;

public:   Reader();    ~Reader();   void addLine(string s);   int getNoOfLines();   string getText();};

Page 28: Introduction to C++ - Duke Computer Science+.pdf · C++ • Data > characteristics • Functions > behavior • Implement all of them in the same “structure” if they belong together

An example (cont’)Reader::Reader(){ no_lines = 0; cout << "constructor called" << endl;}

void Reader::addLine(string s){   no_lines++;  // lines.size();   lines.push_back(s);}

int Reader::getNoOfLines(){  return no_lines;  }

Page 29: Introduction to C++ - Duke Computer Science+.pdf · C++ • Data > characteristics • Functions > behavior • Implement all of them in the same “structure” if they belong together

An example (cont’’)string Reader::getText(){  string s="";  vector<string>::iterator it;  for(it = lines.begin();it != lines.end(); it++)  {    s = s + (*it) + "\n";  }  cout << s;  return s;}

Reader::~Reader(){     lines.erase(lines.begin(),lines.end());     cout << "destructor called" << endl;  }   

Page 30: Introduction to C++ - Duke Computer Science+.pdf · C++ • Data > characteristics • Functions > behavior • Implement all of them in the same “structure” if they belong together

An example (cont’’’)int main(int argc, char* argv[ ]){ int number; for(int i=0;i<argc;i++) {  cout << argv[i] << endl; }

 assert(argc == 3); cout<< "Running Reader!" << endl << "Please provide number of lines to be read number = "; cin >> number; cout << endl;

 cout << "I will read at most " << number << " lines" << endl; 

 string s; ifstream in(argv[1]);  // read from file ofstream out(argv[2]); // write to this file

 Reader* r = new Reader();  while(getline(in,s) && r­>getNoOfLines() < number) {  r­>addLine(s); } 

 string result = r­>getText(); cout << "now see result: " << endl << result << endl ; out << result; delete r;}

Page 31: Introduction to C++ - Duke Computer Science+.pdf · C++ • Data > characteristics • Functions > behavior • Implement all of them in the same “structure” if they belong together

Compilingg++ ­Wall ex1.cc

Don’t forget about –Wall !!!

Page 32: Introduction to C++ - Duke Computer Science+.pdf · C++ • Data > characteristics • Functions > behavior • Implement all of them in the same “structure” if they belong together

ReferencesThinking in C++ 2nd edition Bruce EckelAvailable online at:

http://www.mindview.net/Books/TICPP/ThinkingInCPP2e.html

Vol1 basics about C++Vol2 STL data structures – you will use these !!!