1 / 87

C ++ Programming Languages

Sharif University of Technology. C ++ Programming Languages. Lecturer: Omid Jafarinezhad Fall 2013 Lecture 3. Department of Computer Engineering. Outline. Differences between C and C++ Extensions to C Namespaces String IOStreams (input, output, file ) Function (template, inline).

vito
Download Presentation

C ++ Programming Languages

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. Sharif University of Technology C++ Programming Languages Lecturer: OmidJafarinezhad Fall 2013 Lecture 3 Department of Computer Engineering

  2. Outline Differences between C and C++ Extensions to C Namespaces String IOStreams (input, output, file) Function (template, inline)

  3. Differences between C and C++ • // Ok in C , Error in C ++ • int main() • { • // Error : printf undeclared • printf("Hello World\n"); • } • // Ok in C++ • #include <stdio.h> • int main() • { • printf("Hello World\n"); • } • int main() • { • // Error in C++: return-statement with no value, in function returning 'int' • return; • } // Ok in C++ int main() { } Strict type checking

  4. Extensions to C #include <stdio.h> voidshow(intval) { printf("Integer: %d\n", val); } voidshow(doubleval) { printf("Double: %lf\n", val); } voidshow(char const *val) { printf("String: %s\n", val); } int main() { show(12); show(3.1415); show("Hello World!\n"); } Function Overloading

  5. Extensions to C • Function Overloading: • Do not use function overloading for functions doing conceptually different tasks. • C++ does not allow identically named functions to differ only in their return values.

  6. Extensions to C #include <stdio.h> int Sum(int a = 1, int b = 4) {return a + b;} int main() { printf("%d", Sum()); // arguments: 1 + 4 printf("%d”, Sum(20)); // arguments: 20 + 4 printf("%d", Sum(20, 5)); // arguments: 20 + 5 // Sum(,6); // Error } Default function arguments

  7. Extensions to C // sample header file extern void two_ints(int a = 1, int b = 4); // code of function in, filename.ccp voidtwo_ints(int a, int b) { ... } • Default function arguments • Default arguments must be known at compile-time since at that moment arguments are supplied to functions. Therefore, the default arguments must be mentioned at the function's declaration, rather than at its implementation:

  8. Differences between C and C++ #include <stdio.h> voidshow(intval) { printf("Integer: %d\n", val); } voidshow(doubleval) { printf("Double: %lf\n", val); } voidshow(char const *val) { printf("String: %s\n", val); } int main() { show(0); show(NULL); // show(0); show((char *)0); show(nullptr); // in C++ 11 } NULL-pointers , 0-pointers and nullptr (C++ 11)

  9. Differences between C and C++ #include <stdio.h> voidshow(); int main() { show(10); } voidshow(intval) { printf("Integer: %d\n", val); } C () C++ () The void parameter list

  10. Differences between C and C++ #include <stdio.h> voidshow(void); int main() { show(10); // Error too many arguments to function } voidshow(intval) { printf("Integer: %d\n", val); } C () C++ () The void parameter list

  11. Differences between C and C++ • #include <stdio.h> • int main() • { • for (int i = 0; i < 20; ++i) • printf("%d\n", i); • switch (int c = getchar()) • { • .... • } • if (int c = getchar()) …. • } Defining local variables

  12. Differences between C and C++ structSomeStruct { int a; double d; char string[80]; }; SomeStructwhat; // in c : structSomeStructwhat; what.d = 3.1415; • typedef • The keyword typedefis still used in C++, but is not required anymore when defining union, struct or enum definitions.

  13. Extensions to C #include <stdio.h> int counter = 50; // global variable int main() { intcounter = 10; for (intcounter = 1; // this refers to the counter < 10; // local variable counter++) { printf("%d\n", ::counter // global variable / // divided by counter); // local variable } } • Thescope resolution operator ::

  14. Extensions to C • cout, cin, and cerr • cout, analogous to stdout • cin, analogous to stdin • cerr, analogous to stderr

  15. Extensions to C #include <iostream> using namespace std; int main() { intival; charsval[30]; std::cout<< "Enter a number:\n"; // <<, insertion operator cin >> ival; // >>, extraction operator cout << "And now a string:\n"; cin >> sval; cout<< "The number is: " << ival << "\n" "And the string is: " << sval << '\n'; }

  16. Extensions to C /* in C ++ */ struct Person { char name[80]; char address[80]; void print(); }; void Person::print() { cout << "Name:" << name << "\n" "Address: " << address << "\n"; } Personperson; strcpy(person.name, "Karel"); person.print(); /* in C and C++*/ typedefstruct { char name[80]; char address[80]; } PERSON; /* print information */ void print(PERSON const *p){…} /* etc.. */ Functions as part of a struct

  17. Extensions to C // c++ intint_value; int &ref = int_value; ++int_value; ++ref; // c and c++ intint_value; int *ref = &int_value; ++int_value; ++(*ref); • References • the reference operator & indicates that ref is not itself an int but a reference to one • synonyms for variables • A reference to a variable is like an alias

  18. Extensions to C // c++ void increase(int&valr) { valr += 5; } int main() { int x; increase(x); } // c and c++ void increase(int *valp) { *valp += 5; } int main() { int x; increase(&x); } • References

  19. Extensions to C externint *ip; externint&ir; ip = 0; // reassigns ip, now a 0-pointer ir = 0; // ir unchanged, the int variable it refers to is now 0 int &q;// Error : declared as reference but not initialized • References

  20. Extensions to C int &func() { static intvalue; return value; } int main() { func() = 20; func() += func(); } References could result in extremely ugly code

  21. Extensions to C intintVal() { return 5; } int &ir = intVal(); // fails: refers to a temporary int const &ic = intVal(); // OK: immutable temporary int *ip = &intVal(); // fails: no lvalue available • Rvalue References (C++11) • lvalue reference (typename &) • rvaluereferences (typename &&)

  22. Extensions to C void receive(int &value) // note: lvalue reference { cout << "int value parameter\n"; } void receive(int &&value) // note: rvalue reference { cout << "int R-value parameter\n"; } int main() { receive(18); // int R-value parameter int value = 5; receive(value); // int value parameter receive(intVal()); // int R-value parameter } Rvalue References (C++11)

  23. Memory leak #include <stdlib.h> void function_which_allocates(void) { /* allocate an array of 45 floats */ float * a = malloc(sizeof(float) * 45); /* additional code making use of 'a' */ /* return to main, having forgotten to free the memory we malloc'd */ } int main(void) { function_which_allocates(); /* the pointer 'a' no longer exists, and therefore cannot be freed, but the memory is still allocated. a leak has occurred. */ }

  24. Extensions to C struct Data { char *text; size_t size; void copy(Data const &other) { text = strdup(other.text); size = strlen(text); } }; DatadataFactory(char const *txt) { Data ret = {strdup(txt), strlen(txt)}; return ret; } int main() { Data d1 = {strdup("hello"), strlen("hello")}; Data d2; d2.copy(d1); Data d3; d3.copy(dataFactory("hello")); } Memory leak

  25. Extensions to C struct Data { // …. void copy(Data &&other) { text = other.text; other.text = 0; } }; DatadataFactory(char const *txt) { Data ret = {strdup(txt), strlen(txt)}; return ret; } int main() { Data d1 = {strdup("hello"), strlen("hello")}; Data d2; d2.copy(d1); Data d3; d3.copy(dataFactory("hello")); } Rvalue References (C++11)

  26. Extensions to C enum class SafeEnum { NOT_OK, // 0, by implication OK = 10, MAYBE_OK // 11, by implication }; enum class CharEnum: unsigned char { NOT_OK, OK }; // CharEnum::OK Strongly typed enumerations (C++11)

  27. Extensions to C #include <iostream> using namespace std; enum Color {         RED, // 0         BLUE // 1 }; enum Fruit {         BANANA, // 0         APPLE // 1 }; int main() { Colora = RED; Fruitb = BANANA; // The compiler will compare a and b as integers if (a == b) // and find they are equal! cout << "a and b are equal" << endl; else cout << "a and b are not equal" << endl; return 0; } enumerations in c and c++

  28. Extensions to C #include <iostream> using namespace std; enumclassColor {         RED, // 0         BLUE // 1 }; enumclassFruit {         BANANA, // 0         APPLE // 1 }; • int main() • { • Colora = Color::RED; • Fruitb = Fruit::BANANA; • /* compile error here, as the compiler doesn't know how to compare different types Color and Fruit */ • if (a == b) • cout << "a and b are equal" << endl; • else • cout << "a and b are not equal" << endl; • return 0; • } Strongly typed enumerations (C++11)

  29. Extensions to C auto variable = 5; // int x = 4; auto d = 2.5; // d will be type double autoz = d; // z will be type double autow = "hi"; // w will be type const char* decltype(5) x; // x will be type int because 5 is an int decltype(x) y = 6; // y will be type int because x is an int auto z = x; // z will type typeint int multiply (int x, int y){…} auto multiply (int x, int y) -> int{…} Type inference: auto and decltype(C++11)

  30. Extensions to C #include <iostream> #include <string> // simple function with a default argument, returning nothing void f0(const std::string&arg = "world") { std::cout << "Hello, " << arg << '\n'; } // function returning a pointer to f0, (C++11 style) auto fp11() -> void(*)(const std::string&) { return f0; } // c and c++ (pre-C++11 style) // function returning a pointer to f0 void (*fp03())(const std::string&) { return f0; } int main() { f0(); fp11()("test"); fp03()("again"); } // output Hello, world Hello, test Hello, again function declaration using auto (C++11)

  31. Extensions to C structBigStruct { double array[100]; int last; }; BigStruct data[100]; // assume properly initialized elsewhere intcountUsed() { int sum = 0; // const &: the elements aren't modified for(auto const &element: data) sum += element.last; return sum; } // assume int array[30] for (auto &element: array) statement Range-based for-loops (C++11)

  32. Extensions to C • binary constant • e.g. inti = 0b101; • data types • void, char, short, int, long, float and double • bool, wchar_t, long longand long double • char16_t and char32_t • size_t (typedef long unsigned intsize_t)

  33. Extensions to C boolbValue; // true (!=0) or false (0) bool bValue1 = true; // explicit assignment bool bValue2(false); // implicit assignment bool bValue1 = !true; // bValue1 will have the value false bool bValue2(!false); // bValue2 will have the value true boolbValue = true; // boolbValue = 30; cout << bValue << endl; // 1 cout << !bValue << std::endl; // 0 if (!bValue) cout << "The if statement was true" << endl; else cout << "The if statement was false" << endl; Bool

  34. Extensions to C • The static_cast conversion • static_cast<type>(expression); int x = 19; int y = 4; sqrt(x / y); sqrt(static_cast<double>(x) / y); • The dynamic_cast conversion • The const_cast conversion • The reinterpret_cast conversion

  35. Namespaces // in file1.cpp namespaceCppNS { doublecos(doubleargInDegrees) { ... } } // in file2.cpp namespaceCppNS { double sin(doubleargInDegrees) { ... } } // same as file3.ccp namespaceCppNS { doublecos(doubleargInDegrees) { ... } double sin(doubleargInDegrees) { ... } } Defining namespaces

  36. Namespaces #include <file3> #include <iostream> #include <cmath> using namespace std; int main() { cout << "The cosine of 60 degrees is: " << CppNS::cos(60) << ::cos(60); // call the standard std::cos(60)function } // same as file3.ccp namespaceCppNS { doublecos(doubleargInDegrees) { … } double sin(doubleargInDegrees) { … } } Referring to namespaces

  37. Namespaces #include <file3> #include <iostream> #include <cmath> using namespace std; int main() { using CppNS::cos; /* ... */ cout << cos(60)// calls CppNS::cos() << ::cos(60); // call the standard std::cos(60)function } // same as file3.ccp namespaceCppNS { doublecos(doubleargInDegrees) { … } double sin(doubleargInDegrees) { … } } Referring to namespaces

  38. Namespaces • The standard namespace • The std namespace is reserved by C++ • The standard defines many entities that are part of the runtime available software • e.g., cout, cin, cerr • the templates defined in the Standard Template Library • the Generic Algorithms

  39. Namespaces #include <file3> int main() { CppNS::value = 0; CppNS::Virtual::pointer = 0; } // same as file3.ccp namespaceCppNS { int value; namespace Virtual { void *pointer; } } #include <file3> using namespace CppNS; int main() { value = 0; Virtual::pointer = 0; } Nesting namespaces

  40. Namespaces #include <file3> using namespace CppNS; using namespace Virtual; int main() { value = 0; pointer = 0; } // same as file3.ccp namespaceCppNS { int value; namespace Virtual { void *pointer; } } #include <file3> using namespace CppNS ::Virtual; int main() { CppNS ::value = 0; pointer = 0; } Nesting namespaces

  41. Namespaces #include <file3> namespace CV = CppNS::Virtual; int main() { CV::pointer = 0; } // same as file3.ccp namespaceCppNS { int value; namespace Virtual { void *pointer; } } #include <file3> namespace CV = CppNS::Virtual; using namespace CV; int main() { pointer = 0; } Namespace aliasing

  42. Namespaces #include <file3> namespaceCppNS { namespace Virtual { void *pointer; typedefint INT8[8]; INT8 *squares(); } } // out side the namespace such as in cpp file CppNS::Virtual::INT8 * CppNS ::Virtual::squares() { /* … */ } namespaceCppNS { namespace Virtual { void *pointer; typedefint INT8[8]; INT8 *squares() { /* … */ } } } Defining entities outside of their namespaces

  43. String public class string { /* … */ string&string::operator= (const string& str);string& string::assign (const string& str); string& string::operator= (const char* str);string& string::assign (const char* str);string& string::operator= (char c); /* … */ } • #include <iostream> • #include <string> • using namespace std; • int main() • { • stringsString; • sString = string("One"); • cout << sString << endl;  // One • const string sTwo("Two"); • sString.assign(sTwo); • cout << sString << endl;  // Two • sString = "Three";// Assign a C-style string • cout << sString << endl;  // Three • sString.assign("Four"); • cout << sString << endl;  // Four • sString = '5';// Assign a char • cout << sString << endl;  // 5 • stringsOther; // Chain assignment • sString = sOther = "Six"; • cout << sString << " " << sOther << endl; // Six Six • } std::string

  44. String const string sSource("abcdefg"); stringsDest; sDest.assign(sSource, 2, 4); cout << sDest << endl; // cdef sDest.assign("abcdefg", 4); cout << sDest << endl; // abcd sDest.assign(4, 'g'); cout << sDest << endl; // gggg string sStr1("red"); string sStr2("blue); cout << sStr1 << " " << sStr2 << endl; // red blue swap(sStr1, sStr2); cout << sStr1 << " " << sStr2 << endl; // blue red sStr1.swap(sStr2); cout << sStr1 << " " << sStr2 << endl; // red blue std::string assignment and swapping

  45. String #include <iostream> #include <string> using namespace std; int main() { string sString("aaaa"); cout << sString << endl; // aaaa sString.insert(2, string("bbbb")); cout << sString << endl; // aabbbbaa sString.insert(4, "cccc"); cout << sString << endl; // aabbccccbbaa const string sInsert("01234567"); // insert substring of sInsert from index [3,7) into sString at index 2 sString.insert(2, sInsert, 3, 4); // aa3456bbccccbbaa cout << sString << endl; } std::string inserting

  46. String stringsString("one"); sString += string(" two"); // sString += " two"; stringsThree(" three"); sString.append(sThree); cout << sString << endl; // one two three stringsString("one "); const string sTemp("twothreefour"); // append substring of sTemp starting at index 3 of length 5 sString.append(sTemp, 3, 5); cout << sString << endl; // one three std::string appending

  47. String at access specified character with bounds checking clear clears the contents insert inserts characters erase removes characters compare compares two strings replace replaces specified portion of a string substr returns a substring copy copies characters findfind characters in the string rfind find the last occurrence of a substring find_first_of find first occurrence of characters find_last_of find last occurrence of characters /* … */ • std::string Member functions • http://en.cppreference.com/w/cpp/string/basic_string

  48. String #include <stdexcept> #include <iostream> int main() { std::string s("message"); // for capacity s = "abc"; s.at(2) = 'x'; // ok std::cout << s << '\n'; std::cout << "string size = " << s.size() << '\n'; std::cout << "string capacity = " << s.capacity() << '\n'; try { // throw, even if capacity allowed to access element s.at(3) = 'x'; } catch (std::out_of_range&exc) { std::cout << exc.what() << '\n‘; } } abx string size = 3 string capacity = 7 basic_string::at • std::string Member functions • http://en.cppreference.com/w/cpp/string/basic_string/at

  49. String • stoi Convert string to integer • stol Convert string to long int • stoul Convert string to unsigned integer • stoll Convert string to long long • stoull Convert string to unsigned long long • stof Convert string to float • stod Convert string to double • stold Convert string to long double • intstoi (const string& str, size_t*idx = 0, int base = 10); • std::string str_bin = "-10010110001"; • int i_bin = std::stoi (str_bin,nullptr,2); • std::cout << str_bin << ": " << i_bin; // -10010110001: -1201 • std::string Convert from strings • C++11 added several string conversion functions

  50. IOStreams #include <iostream> using namespace std; int main() { cout << "Enter your age: " << endl; // print text to the monitor intnAge; cin >> nAge; // get input from the user if (nAge <= 0) { // print an error message cerr << "Oops, you entered an invalid age!" << endl; return 1; } cout << "You entered " << nAge << " years old" << endl; return 0; } • Input/output in C++ • istream class, extraction operator (>>) • ostream class, insertion operator (<<)

More Related