A Tour of the C++ Programming Language
|
|
- Mabel Benson
- 5 years ago
- Views:
Transcription
1 A Tour of the C++ Programming Language
2 We already know C Everything that can be done with a computer, can be done in C Why should we learn another language? Newer languages provide a bigger toolbox Some code can be made simpler and shorter using more advanced features In particular, C++ can simplify a lot of the techniques we use in Object Oriented Programming 2
3 What things bother us when writing C code? Explicit memory management is needed We always have to remember ourselves when to free a resource It cannot be encapsulated (i.e., it is not hidden from the user) void printbeststudents(set students, int mingrade) { Set beststudents = setfilter(students, gradegreater, mingrade); if (beststudents == NULL) { return; List sortedstudents = settolist(beststudents); setdestroy(beststudents); if (sortedstudents == NULL) { return; if (listsort(sortedstudents, studentcomparebygrade) == LIST_SUCCESS)) { LIST_FOREACH(Student, student, sortedstudents) { studentprint(student); listdestroy(sortedstudents); 3
4 What things bother us when writing C code? Writing code as ADTs results in long names Student findbeststudent(set students) { SET_FOREACH(Student, student, students) { if (studentgetaverage(student) > studentgetaverage(best)) { best = student; return best; 4
5 What things bother us when writing C code? Generic ADTs (such as our set) Require cumbersome extra code for every type they are used with Require constant use of unsafe pointer casting static char* stringcopy(setelement str); static void stringdestroy(setelement str); static int stringcompare(setelement str1, SetElement str2); Set set = setcreate(stringcopy, stringdestroy, stringcompare); //... setadd(set, student); 5
6 What things bother us when writing C code? Error handling requires a lot of code It can easily become most of the code Each type has its own unique error codes no natural way to translate between them, merge sets of error codes, etc. GraphResult graphaddedge(graph graph, VertexLabel label1, VertexLabel label2) { GraphResult vertex1exists = vertexexists(graph, label1); GraphResult vertex2exists = vertexexists(graph, label1); if (vertex1exists == GRAPH_OUT_OF_MEMORY vertex2exists == GRAPH_OUT_OF_MEMORY) { return GRAPH_OUT_OF_MEMORY; if (vertex1exists == GRAPH_FAIL vertex2exists == GRAPH_FAIL) { return GRAPH_FAIL; Edge edge = edgecreate(label1, label2); if (edge == NULL) { return GRAPH_OUT_OF_MEMORY; SetResult result = setadd(graph->edges, edge); edgedestroy(edge); return convertsetresult(result); 6
7 Originally developed by Bjarne Stroustrup from 1979 Back at the time it was called C with classes The intention was to add useful features from Simula on top of C First release in 1983 as C++ The current standard is C++11 C++ is based on C Adds features to simplify object oriented programming And much more Most C code can be compiled as C++ code However, things are done differently in C++! Using C style paradigms in C++ is bad programming 7
8 C++ is based on C Code looks similar in many cases #include <stdio.h> C #include <iostream> using namespace std; C++ int factorial(int n) { if (n <= 1) { return 1; return n * factorial(n - 1); int factorial(int n) { if (n <= 1) { return 1; return n * factorial(n - 1); int main() { printf("hello World!\n"); printf("5! = %d\n", factorial(5)); return 0; int main() { cout << "Hello world!" << endl; cout << "5! = " << factorial(5) << endl; return 0; 8
9 Classes are the most notable feature of C++ A class is the way provided by C++ to define new data types and ADTs A C++ class can behave much more like a real type than a C ADT Basically, a C++ class is a struct + functions We will call such functions member functions or methods void f() { Complex c1(3,2), c2; c2 = 2 + 5*COMPLEX_I; class Complex { double real, imag; //... more data fields 9 double x = c1.real(); c1.set_real(2*x); cin >> c2; if (c2.imaginary() < 0) { return; if (abs(c1-c2) < 0.001) { cout << "c1 and c2 are equal!\n << endl; public: double real() const; double imaginary() const; void set_real(double); void set_imaginary(double); //... more methods ;
10 C++ tries to avoid uninitialized data Classes have special methods to automatically initialize and destruct them, called constructors and destructors These replace the C style create and destroy functions void f() { Complex c1(3,2), c2; c2 = 2 + 5*COMPLEX_I; double x = c1.real(); c1.set_real(2*x); cin >> c2; if (c2.imaginary() < 0) { return; 10 if (abs(c1-c2) < 0.001) { cout << "c1 and c2 are equal\n << endl;
11 Destructors are extremely useful The compiler automatically calls the destructor when a local object is released This is a major difference from C allows a class to fully encapsulate resource management! void f() { 11 Complex c1(3,2), c2; c2 = 2 + 5*COMPLEX_I; double x = c1.real(); c1.set_real(2*x); cin >> c2; if (c2.imaginary() < 0) { return; if (abs(c1-c2) < 0.001) { cout << "c1 and c2 are equal\n << endl; class Complex { double real, imag; //... more data fields public: Complex(); ~Complex(); double real() const; double imaginary() const; //... more methods ;
12 C++ allows defining custom operators for classes For example, a complex number type can be made to work with +, -, *, / and more void f() { Complex c1(3,2), c2; c2 = 2 + 5*COMPLEX_I; double x = c1.real(); c1.set_real(2*x); cin >> c2; if (c2.imaginary() < 0) { return; 12 if (abs(c1-c2) < 0.001) { cout << "c1 and c2 are equal\n << endl;
13 C++ allows creation of generic code using a template mechanism Template code is checked by the compiler for correctness No need to mess with all function pointers explicitly set<string> strings; string input; while (cin >> input) { if (input == "stop") { break; strings.insert(input); Complex one(1.0, 0.0); strings.insert(one); 13
14 C++ supports inheritance - creating a class B which inherits the behavior of class A Allows creating polymorphic interfaces very easily class Shape { public: virtual double getarea() const; virtual double getperimeter() const; ; class Square : public Shape { public: virtual double getarea() const; virtual double getperimeter() const; ; array<shape*> shapes = { new Square(3.0), new Circle(1.0), new Rectangle(2.0, 4.0) ; double area = 0.0; double maxperimeter = 0.0; for (int i = 0; i < shapes.size(); ++i) { area += shapes[i].getarea(); cout << "The total area is << area << endl; 14
15 C++ supports error handling using an exception mechanism Provides a way for a function to terminate with an error (an exception object), without using return Exceptions require writing code only where the error occurs (thrown) or handled (caught) void f() { //... try { cin >> x; update_values(values,size,x); catch (DivideByZeroException& e) { cerr << "Division by zero!"; void update_values(complex values[], int size, double x) { for (int i = 0; i < size; i++) { values[i] = values[i] / x; Complex operator/ (Complex a, Complex b) { if (b==0) { throw DivideByZeroException(); //... do actual computation 15
16 C++ comes with a Standard Template Library Contains many data structures and algorithms Can be easily extended to cooperate with user code int main(int argc, char **argv) { vector<int> v = { 5, 4, 1, 2, 3 ; sort(v.begin(), v.end()); list<int> l(v.begin(), v.end()); if (find(l.begin(), l.end(), 4)!= l.end()) { cout << "found" << endl; return 0; 16
17 C++11 is a fairly new standard As such, it is not fully implemented yet The latest version of G++ (GCC s C++ compiler) handles almost all of the standard's features Features which are C++11 only will be marked You can solve your homework using these C++11 features, but it s not mandatory 17
18 C++ is much more advanced than C Takes more time to master However: DON T PANIC Understanding even only the basic features can simplify a lot of your work 18
19 C++ is similar to C However, there are some elementary differences We will first cover a few of enhancements needed before we can move on 19
20 C++ has the const keyword which is used as in C99 We will see that const is used much more widely in C++ const int n = 5; const int* ptr = &n; int* const cptr = &n; // error const int* const cptr2 = &n; Const correctness is about indicating which objects change and which don't, and ensuring consistency The goal is letting the compiler (and reader) find errors easily 20
21 C++ allows defining a reference to a variable The notation T& means reference to type T A reference acts as an alternative name for a variable int i = 1; int& r = i; int x = r; r = 2; 21
22 References must be initialized int& r; Once initialized, a reference target cannot be changed int ii = 0; int& rr = ii; rr++; int* pp = &rr; A reference is similar to a constant pointer However, a reference isn't an object that can be manipulated like a pointer A reference always refers to a legal object 22
23 References can be used as function arguments Can be used when a function has to modify its arguments void swap(int& a, int& b) { int temp = a; a = b; b = a; int a = 5; int b = 3; swap(a, b); Like the address-of operator &, a reference cannot refer to a temporary value or a constant swap(a, 3); swap(a, x + y); 23
24 References can also be used as a return value int& max(int array[], int size) { int maxindex = 0; for(int i = 1; i < size; i++) { if (array[i] > array[maxindex]) { maxindex = i; return array[maxindex]; References can serve as a left-hand-side (LHS) in assignment This seems weird for now, but has many natural uses int array[] = { 1, 3, 4, 2, 5 ; max(array, 5) = 7; 24
25 A reference can be declared to refer to a const In this case the object referenced cannot be changed through the reference A const reference can refer to a temporary value void print(const int& r) { cout << r << endl; int a = 5; print(3); print(3 + a); 25
26 C++ allows definition of several functions with the same name The functions are overloaded on the name These functions must have different enough parameters The compiler chooses the function which fits best void swap(int&, int&); void swap(double&, double&); int a, b; double c,d; swap(a,b); // calls first swap swap(c,d); // calls second swap swap(a,c); // syntax error 26
27 C++ allows defining a default value for a function argument The function may be called without this argument, in which case the default value is passed Several of the arguments may have default values, but they must be the last ones static void printnumbers(int to = 10) { for (int i = 0; i < to; ++i) { cout << i << ", "; cout << endl; printnumbers(5); printnumbers(); // printnumbers(10); or num_utils.h void printnumbers(int to = 10); num_utils.c void printnumbers(int to) { for (int i = 0; i < to; ++i) { cout << i << ", "; cout << endl; 27
28 Default arguments are useful when one of the arguments has a common value which is used frequently void sort(int array[], int size, int (*compare)(int, int) = compareints) { for (int i = 0; i < size; ++i) { for (int j = 0; j < size - 1; ++j) { if (compare(array[j], array[j + 1]) > 0) { swap(array[j], array[j + 1]); int compareints(int a, int b) { return a - b; int compareinverse(int a, int b) { return b - a; int array[] = {3, 4, 2, 1, 5; int size = sizeof(array) / sizeof(array[0]); sort(array, size); // sort(array, size, compareints); sort(array, size, compareinverse); 28
29 There is no implicit cast from void* to other pointers in C++ C++ has better mechanisms in order to avoid the need of such casts Pointer casting should be avoided in C++ There are better solutions int* ptr = malloc(sizeof(*ptr)); int* ptr = (int*)malloc(sizeof(*ptr)); 29
30 Memory allocations are done in C++ using the new and delete operators new & delete are typed Unlike malloc and free, which use void* new initializes an object, and delete calls its destructor So there is no uninitialized memory containing garbage Built in types (such as int) can still be allocated without initialization if needed int* ptr = malloc(sizeof(*ptr)); *ptr = 5; int* array = malloc(sizeof(*array) * 10); //... need to verify allocations... C int* ptr = new int(5); int* array = new int[10](); //... C++ free(ptr); free(array); delete ptr; delete[] array; 30
31 All code in C++ is divided into a hierarchical structure of namespaces Think of namespaces like folders in a file system namespace fast_math { double sqrt(double); double cos(double); double sin(double); void f(double& d) { cout << std::sqrt(d) << endl; cout << fast_math::sqrt(d) << endl; 31
32 Namespaces can be nested namespace mtm { namespace ex4 { enum ErrorCode { OUT_OF_MEMORY,... ; printerror(errorcode e); mtm::ex4::printerror(mtm::ex4::out_of_memory); std::cout << "Error!" << std::endl; A using statement can be used to define which implementation we want in this part of the code using std::cout; using std::endl; using namespace mtm::ex4; printerror(out_of_memory); cout << "Error!" << endl; 32
33 The C language combines all the power of assembly language with all the ease-of-use of assembly language. - Mark Pearce 33
A Tour of the C++ Programming Language
A Tour of the C++ Programming Language We already know C Everything that can be done with a computer, can be done in C Why should we learn another language? Newer languages provide a bigger toolbox Some
More informationAnnouncements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy
CSCI 334: Principles of Programming Languages Lecture 18: C/C++ Homework help session will be tomorrow from 7-9pm in Schow 030A instead of on Thursday. Instructor: Dan Barowy HW6 and HW7 solutions We only
More informationFast Introduction to Object Oriented Programming and C++
Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming
More informationEvolution of Programming Languages
Evolution of Programming Languages 40's machine level raw binary 50's assembly language names for instructions and addresses very specific to each machine 60's high-level languages: Fortran, Cobol, Algol,
More informationEL2310 Scientific Programming
(pronobis@kth.se) Overview Overview Wrap Up Introduction to Object Oriented Paradigm More on and Members Operator Overloading Last time Intro to C++ Differences between C and C++ Intro to OOP Today Object
More informationWhere do we go from here?
Where do we go from here? C++ classes and objects, with all the moving parts visible operator overloading templates, STL, standards, Java components, collections, generics language and performance comparisons
More informationLecture 8: Object-Oriented Programming (OOP) EE3490E: Programming S1 2017/2018 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology
Lecture 8: Object-Oriented Programming (OOP) 1 Introduction to C++ 2 Overview Additional features compared to C: Object-oriented programming (OOP) Generic programming (template) Many other small changes
More informationAN OVERVIEW OF C++ 1
AN OVERVIEW OF C++ 1 OBJECTIVES Introduction What is object-oriented programming? Two versions of C++ C++ console I/O C++ comments Classes: A first look Some differences between C and C++ Introducing function
More informationPointers, Dynamic Data, and Reference Types
Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation The new operator The delete operator Dynamic Memory Allocation for Arrays 1 C++ Data Types simple
More informationCSCI 102L - Data Structures Midterm Exam #1 Fall 2011
Print Your Name: Page 1 of 8 Signature: Aludra Loginname: CSCI 102L - Data Structures Midterm Exam #1 Fall 2011 (10:00am - 11:12am, Wednesday, October 5) Instructor: Bill Cheng Problems Problem #1 (24
More informationbeginslide Chapter 6 The C++ Programming Language The Role of Classes
1 Chapter 6 The C++ Programming Language The Role of Classes 2 C++ as Enhanced C Stronger typing. Inline functions. Call by reference. Function prototypes and overloading. Default function parameters.
More informationIntroduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts
Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter
More informationCS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE
CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE PART A UNIT I 1. Differentiate object oriented programming from procedure oriented programming. 2. Define abstraction and encapsulation. 3. Differentiate
More informationCS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms
CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms AUTO POINTER (AUTO_PTR) //Example showing a bad situation with naked pointers void MyFunction()
More information1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!
//Example showing a bad situation with naked pointers CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms void MyFunction() MyClass* ptr( new
More informationA brief introduction to C++
A brief introduction to C++ Rupert Nash r.nash@epcc.ed.ac.uk 13 June 2018 1 References Bjarne Stroustrup, Programming: Principles and Practice Using C++ (2nd Ed.). Assumes very little but it s long Bjarne
More informationAgenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures
The main body and cout Agenda 1 Fundamental data types Declarations and definitions Control structures References, pass-by-value vs pass-by-references The main body and cout 2 C++ IS AN OO EXTENSION OF
More informationIntroduction to C++ Systems Programming
Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions
More informationCSC 330 Object-Oriented Programming. Exception Handling CSC 330
Object-Oriented Programming Exception Handling 1 C++ Exception Handling Topics Exception Handling C++ Exception Handling Basics Throwing and Catching Exceptions Constructors, Destructors and Exceptions
More informationMore Functions. Pass by Value. Example: Exchange two numbers. Storage Classes. Passing Parameters by Reference. Pass by value and by reference
Pass by Value More Functions Different location in memory Changes to the parameters inside the function body have no effect outside of the function. 2 Passing Parameters by Reference Example: Exchange
More informationCSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010
CSE 374 Programming Concepts & Tools Hal Perkins Spring 2010 Lecture 19 Introduction ti to C++ C++ C++ is an enormous language: g All of C Classes and objects (kind of like Java, some crucial differences)
More informationShort Notes of CS201
#includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system
More informationCE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings
CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings 19/10/2017 CE221 Part 2 1 Variables and References 1 In Java a variable of primitive type is associated with a memory location
More informationCS201 - Introduction to Programming Glossary By
CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with
More informationA506 / C201 Computer Programming II Placement Exam Sample Questions. For each of the following, choose the most appropriate answer (2pts each).
A506 / C201 Computer Programming II Placement Exam Sample Questions For each of the following, choose the most appropriate answer (2pts each). 1. Which of the following functions is causing a temporary
More informationCS24 Week 3 Lecture 1
CS24 Week 3 Lecture 1 Kyle Dewey Overview Some minor C++ points ADT Review Object-oriented Programming C++ Classes Constructors Destructors More minor Points (if time) Key Minor Points const Motivation
More informationHomework 4. Any questions?
CSE333 SECTION 8 Homework 4 Any questions? STL Standard Template Library Has many pre-build container classes STL containers store by value, not by reference Should try to use this as much as possible
More informationCS
CS 1666 www.cs.pitt.edu/~nlf4/cs1666/ Programming in C++ First, some praise for C++ "It certainly has its good points. But by and large I think it s a bad language. It does a lot of things half well and
More informationC++ Primer for CS175
C++ Primer for CS175 Yuanchen Zhu September 10, 2014 This primer is pretty long and might scare you. Don t worry! To do the assignments you don t need to understand every point made here. However this
More informationCSE 303: Concepts and Tools for Software Development
CSE 303: Concepts and Tools for Software Development Hal Perkins Autumn 2008 Lecture 24 Introduction to C++ CSE303 Autumn 2008, Lecture 24 1 C++ C++ is an enormous language: All of C Classes and objects
More informationG52CPP C++ Programming Lecture 16
G52CPP C++ Programming Lecture 16 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last Lecture Casting static cast dynamic cast const cast reinterpret cast Implicit type conversion 2 How
More informationTokens, Expressions and Control Structures
3 Tokens, Expressions and Control Structures Tokens Keywords Identifiers Data types User-defined types Derived types Symbolic constants Declaration of variables Initialization Reference variables Type
More informationCSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 19 Introduction to C++ C++ C++ is an enormous language: All of C Classes and objects (kind of like Java, some crucial differences) Many
More informationIntroduction to Programming using C++
Introduction to Programming using C++ Lecture One: Getting Started Carl Gwilliam gwilliam@hep.ph.liv.ac.uk http://hep.ph.liv.ac.uk/~gwilliam/cppcourse Course Prerequisites What you should already know
More informationCOMP322 - Introduction to C++
COMP322 - Introduction to C++ Winter 2011 Lecture 2 - Language Basics Milena Scaccia School of Computer Science McGill University January 11, 2011 Course Web Tools Announcements, Lecture Notes, Assignments
More informationEL2310 Scientific Programming
Lecture 14: Object Oriented Programming in C++ (ramviyas@kth.se) Overview Overview Lecture 14: Object Oriented Programming in C++ Classes (cont d) More on Classes and Members Group presentations Last time
More informationInterview Questions of C++
Interview Questions of C++ Q-1 What is the full form of OOPS? Ans: Object Oriented Programming System. Q-2 What is a class? Ans: Class is a blue print which reflects the entities attributes and actions.
More information15: Polymorphism & Virtual Functions
15: Polymorphism & Virtual Functions 김동원 2003.02.19 Overview virtual function & constructors Destructors and virtual destructors Operator overloading Downcasting Thinking in C++ Page 1 virtual functions
More informationSTRUCTURING OF PROGRAM
Unit III MULTIPLE CHOICE QUESTIONS 1. Which of the following is the functionality of Data Abstraction? (a) Reduce Complexity (c) Parallelism Unit III 3.1 (b) Binds together code and data (d) None of the
More informationIntermediate Programming, Spring 2017*
600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general
More informationEL2310 Scientific Programming
Lecture 14: Object Oriented Programming in C++ (fpokorny@kth.se) Overview Overview Lecture 14: Object Oriented Programming in C++ Wrap Up Introduction to Object Oriented Paradigm Classes More on Classes
More informationCSE 333 Lecture 9 - intro to C++
CSE 333 Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington Administrivia & Agenda Main topic: Intro to C++ But first: Some hints on HW2 Labs: The
More informationQUIZ. What is wrong with this code that uses default arguments?
QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code
More informationCS 11 C++ track: lecture 1
CS 11 C++ track: lecture 1 Administrivia Need a CS cluster account http://www.cs.caltech.edu/cgi-bin/ sysadmin/account_request.cgi Need to know UNIX (Linux) www.its.caltech.edu/its/facilities/labsclusters/
More informationOutline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C
Lecture 1 C primer What we will cover A crash course in the basics of C You should read the K&R C book for lots more details Various details will be exemplified later in the course Outline Overview comparison
More informationProcedures, Parameters, Values and Variables. Steven R. Bagley
Procedures, Parameters, Values and Variables Steven R. Bagley Recap A Program is a sequence of statements (instructions) Statements executed one-by-one in order Unless it is changed by the programmer e.g.
More informationObject Oriented Programming using C++
Object Oriented Programming using C++ Overview Problem Solving Features of an OOL Basic Syntax Programming Paradigms Solving a Programming Problem Analysis Design Coding Management Programming paradigms
More informationProgramming in C++: Assignment Week 8
Programming in C++: Assignment Week 8 Total Marks : 20 September 9, 2017 Question 1 Consider the following code segment. Mark 2 void myfunction(int test) { try { if (test) throw test; else throw "Value
More informationWhat will happen if we try to compile, link and run this program? Do you have any comments to the code?
1 # include < iostream > 2 3 int main () 4 { 5 std :: cout
More informationInheritance, and Polymorphism.
Inheritance and Polymorphism by Yukong Zhang Object-oriented programming languages are the most widely used modern programming languages. They model programming based on objects which are very close to
More informationPOINTERS - Pointer is a variable that holds a memory address of another variable of same type. - It supports dynamic allocation routines. - It can improve the efficiency of certain routines. C++ Memory
More informationC++ for Java Programmers
Basics all Finished! Everything we have covered so far: Lecture 5 Operators Variables Arrays Null Terminated Strings Structs Functions 1 2 45 mins of pure fun Introduction Today: Pointers Pointers Even
More informationAbsolute C++ Walter Savitch
Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents
More informationCS 376b Computer Vision
CS 376b Computer Vision 09 / 25 / 2014 Instructor: Michael Eckmann Today s Topics Questions? / Comments? Enhancing images / masks Cross correlation Convolution C++ Cross-correlation Cross-correlation involves
More informationG52CPP C++ Programming Lecture 14. Dr Jason Atkin
G52CPP C++ Programming Lecture 14 Dr Jason Atkin 1 Last Lecture Automatically created methods: A default constructor so that objects can be created without defining a constructor A copy constructor used
More informationSoftware Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example
Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example CS 311 Data Structures and Algorithms Lecture Slides Friday, September 11, 2009 continued Glenn G. Chappell
More informationPolymorphism Part 1 1
Polymorphism Part 1 1 What is Polymorphism? Polymorphism refers to a programming language s ability to process objects differently depending on their data type or class. Number person real complex kid
More informationKingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS
Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 1 ARRAYS Arrays 2 Arrays Structures of related data items Static entity (same size
More informationObject Oriented Programming. Solved MCQs - Part 2
Object Oriented Programming Solved MCQs - Part 2 Object Oriented Programming Solved MCQs - Part 2 It is possible to declare as a friend A member function A global function A class All of the above What
More informationReference Parameters A reference parameter is an alias for its corresponding argument in the function call. Use the ampersand (&) to indicate that
Reference Parameters There are two ways to pass arguments to functions: pass-by-value and pass-by-reference. pass-by-value A copy of the argument s value is made and passed to the called function. Changes
More informationPointers. Developed By Ms. K.M.Sanghavi
Pointers Developed By Ms. K.M.Sanghavi Memory Management : Dynamic Pointers Linked List Example Smart Pointers Auto Pointer Unique Pointer Shared Pointer Weak Pointer Memory Management In order to create
More informationG52CPP C++ Programming Lecture 20
G52CPP C++ Programming Lecture 20 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Wrapping up Slicing Problem Smart pointers More C++ things Exams 2 The slicing problem 3 Objects are not
More informationCA341 - Comparative Programming Languages
CA341 - Comparative Programming Languages David Sinclair Dynamic Data Structures Generally we do not know how much data a program will have to process. There are 2 ways to handle this: Create a fixed data
More informationIS 0020 Program Design and Software Tools
1 Introduction 2 IS 0020 Program Design and Software Tools Exception Handling Lecture 12 November 23, 200 Exceptions Indicates problem occurred in program Not common An "exception" to a program that usually
More informationC++ Namespaces, Exceptions
C++ Namespaces, Exceptions CSci 588: Data Structures, Algorithms and Software Design http://www.cplusplus.com/doc/tutorial/namespaces/ http://www.cplusplus.com/doc/tutorial/exceptions/ http://www.cplusplus.com/doc/tutorial/typecasting/
More informationC++ Important Questions with Answers
1. Name the operators that cannot be overloaded. sizeof,.,.*,.->, ::,? 2. What is inheritance? Inheritance is property such that a parent (or super) class passes the characteristics of itself to children
More informationChapter 2. Procedural Programming
Chapter 2 Procedural Programming 2: Preview Basic concepts that are similar in both Java and C++, including: standard data types control structures I/O functions Dynamic memory management, and some basic
More informationObject Reference and Memory Allocation. Questions:
Object Reference and Memory Allocation Questions: 1 1. What is the difference between the following declarations? const T* p; T* const p = new T(..constructor args..); 2 2. Is the following C++ syntax
More informationC++_ MARKS 40 MIN
C++_16.9.2018 40 MARKS 40 MIN https://tinyurl.com/ya62ayzs 1) Declaration of a pointer more than once may cause A. Error B. Abort C. Trap D. Null 2Whice is not a correct variable type in C++? A. float
More informationCS349/SE382 A1 C Programming Tutorial
CS349/SE382 A1 C Programming Tutorial Erin Lester January 2005 Outline Comments Variable Declarations Objects Dynamic Memory Boolean Type structs, enums and unions Other Differences The Event Loop Comments
More informationProgrammazione. Prof. Marco Bertini
Programmazione Prof. Marco Bertini marco.bertini@unifi.it http://www.micc.unifi.it/bertini/ Hello world : a review Some differences between C and C++ Let s review some differences between C and C++ looking
More informationstruct Buffer { Buffer(int s) { buf = new char[s]; } ~Buffer() { delete [] buf; } char *buf; };
struct Buffer { Buffer(int s) { buf = new char[s]; ~Buffer() { delete [] buf; char *buf; ; struct FBuffer : public Buffer { FBuffer(int s) : Buffer(s) { f = fopen("file", "w"); ~FBuffer() { fclose(f);
More informationCS3157: Advanced Programming. Outline
CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching
More informationIntroduction to C++ Introduction to C++ 1
1 What Is C++? (Mostly) an extension of C to include: Classes Templates Inheritance and Multiple Inheritance Function and Operator Overloading New (and better) Standard Library References and Reference
More informationIntroduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.
Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. 9 Self-Test Exercises p. 11 History Note p. 12 Programming and
More informationC++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15
C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15 This chapter introduces the notion of dynamic memory allocation of variables and objects in a C++ program.
More informationObject-Oriented Programming, Iouliia Skliarova
Object-Oriented Programming, Iouliia Skliarova CBook a = CBook("C++", 2014); CBook b = CBook("Physics", 1960); a.display(); b.display(); void CBook::Display() cout
More informationSTUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING
OBJECT ORIENTED PROGRAMMING STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING 1. Object Oriented Programming Paradigms 2. Comparison of Programming Paradigms 3. Basic Object Oriented Programming
More informationCOMP 2355 Introduction to Systems Programming
COMP 2355 Introduction to Systems Programming Christian Grothoff christian@grothoff.org http://grothoff.org/christian/ 1 Today Class syntax, Constructors, Destructors Static methods Inheritance, Abstract
More informationJayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT
CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT Two Mark Questions UNIT - I 1. DEFINE ENCAPSULATION. Encapsulation is the process of combining data and functions
More informationSeptember 10,
September 10, 2013 1 Bjarne Stroustrup, AT&T Bell Labs, early 80s cfront original C++ to C translator Difficult to debug Potentially inefficient Many native compilers exist today C++ is mostly upward compatible
More informationADTs in C++ In C++, member functions can be defined as part of a struct
In C++, member functions can be defined as part of a struct ADTs in C++ struct Complex { ; void Complex::init(double r, double i) { im = i; int main () { Complex c1, c2; c1.init(3.0, 2.0); c2.init(4.0,
More informationC++ For C Programmers Week 1 Part 1
C++ For C Programmers Week 1 Part 1 Overview and Course Organization C++ as a Better C Problem 1 Convert C Code to be posted Course work 1. Homework 3 Programs to Code 2. One Final- closed book C++ is
More informationWhere do we go from here?
Lecture 16: C++ Where do we go from here? C++ classes and objects, with all the moving parts visible operator overloading templates, STL, standards, Java Go components, collections, generics language and
More informationANSI C. Data Analysis in Geophysics Demián D. Gómez November 2013
ANSI C Data Analysis in Geophysics Demián D. Gómez November 2013 ANSI C Standards published by the American National Standards Institute (1983-1989). Initially developed by Dennis Ritchie between 1969
More informationCS102 C++ Exception Handling & Namespaces
CS102 C++ Exception Handling & Namespaces Bill Cheng http://merlot.usc.edu/cs102-s12 1 Topics to cover C Structs (Ch 10) C++ Classes (Ch 11) Constructors Destructors Member functions Exception Handling
More informationLab 2: Pointers. //declare a pointer variable ptr1 pointing to x. //change the value of x to 10 through ptr1
Lab 2: Pointers 1. Goals Further understanding of pointer variables Passing parameters to functions by address (pointers) and by references Creating and using dynamic arrays Combing pointers, structures
More information05-01 Discussion Notes
05-01 Discussion Notes PIC 10B Spring 2018 1 Exceptions 1.1 Introduction Exceptions are used to signify that a function is being used incorrectly. Once an exception is thrown, it is up to the programmer
More informationProblem Solving with C++
GLOBAL EDITION Problem Solving with C++ NINTH EDITION Walter Savitch Kendrick Mock Ninth Edition PROBLEM SOLVING with C++ Problem Solving with C++, Global Edition Cover Title Copyright Contents Chapter
More informationProgram Organization and Comments
C / C++ PROGRAMMING Program Organization and Comments Copyright 2013 Dan McElroy Programming Organization The layout of a program should be fairly straight forward and simple. Although it may just look
More informationFinal CSE 131B Spring 2004
Login name Signature Name Student ID Final CSE 131B Spring 2004 Page 1 Page 2 Page 3 Page 4 Page 5 Page 6 Page 7 Page 8 (25 points) (24 points) (32 points) (24 points) (28 points) (26 points) (22 points)
More information6.096 Introduction to C++ January (IAP) 2009
MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. Welcome to 6.096 Lecture
More informationWhy VC++ instead of Dev C++?
Why VC++ instead of Dev C++? I love UNIX! I am proficient in UNIX! I like public domain open source software. I love GPL. I was more confident in GCC than in Microsoft C. But! The software business has
More information1 of 8 3/28/2010 8:03 AM C++ Special Topics Home Class Info Links Lectures Newsgroup Assignmen This is a short review of special topics in C++ especially helpful for various assignments. These notes are
More informationCPSC 427: Object-Oriented Programming
CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 22 November 28, 2016 CPSC 427, Lecture 22 1/43 Exceptions (continued) Code Reuse Linear Containers Ordered Containers Multiple Inheritance
More information(5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University
(5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University Key Concepts 2 Object-Oriented Design Object-Oriented Programming
More informationCS250 Final Review Questions
CS250 Final Review Questions The following is a list of review questions that you can use to study for the final. I would first make sure you review all previous exams and make sure you fully understand
More informationOutline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.
Outline Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples. 1 Arrays I Array One type of data structures. Consecutive group of memory locations
More informationIntroducing C++ to Java Programmers
Introducing C++ to Java Programmers by Kip Irvine updated 2/27/2003 1 Philosophy of C++ Bjarne Stroustrup invented C++ in the early 1980's at Bell Laboratories First called "C with classes" Design Goals:
More informationExercise 1.1 Hello world
Exercise 1.1 Hello world The goal of this exercise is to verify that computer and compiler setup are functioning correctly. To verify that your setup runs fine, compile and run the hello world example
More information