Introduction. namespaces Program has identifiers in different scopes Sometimes scopes overlap, lead to problems. Accessing the Variables.
|
|
- Hope Thompson
- 5 years ago
- Views:
Transcription
1 Introduction CSC 330 Object Oriented Design s C++ was developed in early 1980s by Bjarne Stroustrup (AT&T). It was formulated by adding object oriented (and other) features to C, and removing a few bad C features. The primary inspiration came from the language Simula 67. The first commercial release of C++ was in s A namespace is a collection of name definitions, such as class definitions and variable declarations If a program uses classes and functions written by different programmers, it may be that the same name is used for different things s help us deal with this problem 9.2 namespaces Program has identifiers in different scopes Sometimes scopes overlap, lead to problems defines scope Place identifiers and variables within namespace Access with namespace_name::member Note guaranteed to be unique namespace Name contents 4 Unnamed namespaces are global Need no qualification s can be nested 3 4 Example Accessing the Variables 5 6
2 using Declaration or namespace cont d namespaces using statement using namespace namespace_name; Members of that namespace can be used without preceding namespace_name:: Can also be used with individual member Examples using namespace std Discouraged by some programmers, because includes entire contents of std using namespace std::cout Can write cout instead of std::cout using Declarations and Directives To avoid the tedium of std::cout << "Please enter stuff \n"; you could write a using declaration using std::cout; // when I say cout,, I mean std::cout cout << "Please enter stuff \n"; // ok: std::cout cin >> x; // error: cin not in scope or you could write a using directive // make all names from namespace std available cout << "Please enter stuff \n"; // ok: std::cout cin >> x; // ok: std::cin s A namespace is a named scope The :: syntax is used to specify which namespace you are using and a which (of many possible) objects of the same name you are referring to For example, cout is in namespace std,, you could write: std::cout << "Please enter stuff \n"; // Demonstrating namespaces. Note the using 3 #include <iostream> 4 statement. This includes 5 // use std namespace all of std, allowing us to 6 use cout and endl. 7 int integer1 = 98; // global variable 8 9 // create namespace Example 10 namespace Example Create a new 11 namespace, Example. 12 // declare two constants and one variable Note that it has a variable 13 const double PI = ; integer1, different from 14 const double E = ; the global integer1. 15 int integer1 = 8; Create an unnamed 29 // create unnamed namespace 30 namespace namespace. Its variables 31 double doubleinunnamed = 88.22; // declare variable are global // end unnamed namespace int main() // output value doubleinunnamed of unnamed namespace 38 cout << "doubleinunnamed = " << doubleinunnamed; // output global variable 41 cout << "\n(global) integer1 = " << integer1; // output values of Example namespace void printvalues(); // prototype 44 cout << "\npi = " << Example::PI << "\ne = " // nested namespace 20 namespace Inner // define enumeration Note the nested namespace Inner. 45 << Example::E << "\ninteger1 = " 46 << Example::integer1 << "\nfiscal3 = " 47 << Example::Inner::FISCAL3 << endl; Example::printValues(); // invoke printvalues function 23 enum Years FISCAL1 = 1990, FISCAL2, FISCAL3 ; return 0; 25 // end Inner // end main 27 // end Example 11 12
3 54 55 // display variable and constant values 13 doubleinunnamed = (global) integer1 = void Example::printValues() PI = cout << "\nin printvalues:\ninteger1 = " 59 << integer1 << "\npi = " << PI << "\ne = " 60 << E << "\ndoubleinunnamed = " << doubleinunnamed 61 << "\n(global) integer1 = " << ::integer1 62 << "\nfiscal3 = " << Inner::FISCAL3 << endl; // end printvalues E = integer1 = 8 FISCAL3 = 1992 In printvalues: integer1 = 8 PI = E = doubleinunnamed = (global) integer1 = 98 FISCAL3 = 1992 fig22_03.c pp output (1 of 1) Name Conflicts If the same name is used in two namespaces The namespaces cannot be used at the same time Example: If my_function is defined in namespaces ns1 and ns2, the two versions of my_function could be used in one program by using local using directives this way: using namespace ns1; my_function( ); using namespace ns2; my_function( ); 15 s Consider this code from two programmers Jack and Jill class Glob /**/ */ ; // in Jack s s header file jack.h class Widget /**/ */ ; // also in jack.h class Blob /**/ */ ; // in Jill s s header file jill.h class Widget /**/ */ ; // also in jill.h #include "jack.h" jack.h"; // this is in your code #include "jill.h" jill.h"; // so is this void my_func(widget p) // oops! error: multiple definitions of Widget // s The compiler will not compile multiple definitions; such clashes can occur from multiple headers. One way to prevent this problem is with namespaces: namespace Jack // in Jack s s header file class Glob /**/ */ ; class Widget /**/ */ ; Name Spaces Definition A namespace is an encapsulation unit used to group declarations and definitions with a common scope. s can encapsulate the following kinds of declarations: Constant and variable declarations Struct, union, and class declarations Function prototypes Function definitions Nested namespaces. #include "jack.h" jack.h"; // this is in your code #include "jill.h" jill.h"; // so is this void my_func(jack::widget p) // OK, Jack s s Widget class will not // clash with a different Widget //
4 s cont d There are three kinds of namespaces: Global namespace: an anonymous namespace composed of all non-static external declarations that do not belong to any other named or unnamed namespace. Select visibility is enabled via the anonymous scope resolution operator (::identifier). Translation unit (TU) namespaces: unnamed namespaces defined within a file; they limit the scope of external declarations to the given file; each file defines a unique TU namespace (if declared); TU namespaces obviate the need for global static declarations; declarations in TU namespaces and global declarations are indistinguishable within the same file only global declarations can have visibility outside the file in which they are defined. Select visibility is enabled via the anonymous scope resolution operator (::). Named namespaces: have an associated identifier that must be unique among all named namespaces. Select visibility is enabled via the scope resolution operator (namespace-id::identifier). s USES 1. To organize a group of modules for independent and parallel develop by different teams (or individuals). By limiting the scope of names to the namespace, naming conflicts can be avoided when independently developed namespaces are integrated after development. 2. To organize a group of related classes that have a common purpose in the design. For example, subsystems may be encapsulated by namespaces. 3. To implement one-of-a-kind objects (efficiently) without having to create the extra overhead associated with defining classes and restricting the number of instances that can be created Name Spaces Named namespaces Translation Unit (one per file) Named Global Translation Unit (one per file) Named Translation Unit (one per file) Named One file namespace alpha int One; typedef int *INTPTR; INTPTR copyint( int value ) One = value; INTPTR p = new int(one); return p; //copyint //alpha int main() alpha::intptr p; int x = 25; p = alpha::copyint(x); The namespace alpha is directly visible it is declared in the global namespace. Names defined within alpha must be referenced using the scope resolution operator (::), since they are not directly (globally) visible Three files NOTE: The 3-file approach is preferred. #include "alpha.h" int main() alpha::intptr p,q; int x = 25; p = alpha::copyint(x); q = alpha::copyint(alpha::one); Named namespaces alpha.h #ifndef ALPHA #define ALPHA namespace alpha extern int One; //data declaration typedef int *INTPTR; INTPTR copyint( int value ); //fn decl. //alpha #endif alpha.cpp #include alpha.h namespace alpha int One; //data definition typedef int *INTPTR; INTPTR copyint( int value ) //fn defn One = value; INTPTR p = new int(one); return p; //copyint //alpha 23 File1.cpp #include <iostream> #include <string> #include alpha.h void f( float ); // global fn prototype; int main() alpha::intptr p; int x = 25; p = alpha::copyint(x); cout << p = << *p << endl; cout << alpha::one = << alpha::one << endl; f( float(x)); // type conversion Extension An extension to alpha File2.cpp File2.cpp Local to File2.cpp #include <iostream> #include <string> namespace alpha typedef float *FLTPTR; float Two = 0.0; FLTPTR copyflt( float value ) //fn defn Two = value; FLTPTR p = new float(two); return p; //copyflt //alpha //code that uses the local extensions to alpha 24
5 Alpha.h Extension #ifndef ALPHA #define ALPHA namespace alpha extern int One; //data declaration typedef int *INTPTR; INTPTR copyint( int value ); //fn decl. extern float Two; //data declaration typedef int *FLTPTR; FLTPTR copyflt( float value ); //fn decl. //alpha #endif Any other files that need to reference Information defined in namespace Alpha Only need to include Alpha.h to gain use of features contributed by both File1.cpp and File2.cpp 25 TU namespaces File1.cpp #include <iostream> #include <string> #include <math> extern double pi; //defined in another file double h( double ), h2(double); namespace // scope limited to this file double f( double x) return x * sqrt(x) //f //namespace double g(double x) // global namespace return sqrt(x)/x; //g int main() double y = 25.0*pi; cout << y^1.5 = << f(y) << endl; cout << y^-0.5 = << g(y) << endl; // main File2.cpp double g( double ); // refers to g in file 1 namespace // visible to h() and h2() const double pi = ; double f( double x) return x * g(x); //f //TU namespace double h( double y) return y/f(y); //h double h2( double y) return pi*y*g(y); //h2 This pi hides ::pi and is only visible in File2. Refers to the local pi not ::pi 26 declarations and directives Using Declarations A using declaration adds a specific name declared in a namespace to the local frame where the using declaration is specified. Using Directive A using directive applies to namespaces as a whole, and simply makes all names declared in the namespace directly visible (without the scope resolution operator). namespace beta int X, Y,Z; int Z; // global Z int main() int X = 0; // local X using namespace beta; //directive X++; // local X Y++; // beta::y Z++; // error (::Z or beta::z )? ::Z++; // global Z beta::z++; // beta Z... namespace beta int X, Y,Z; int Z; // global Z int main() int X = 0; // local X using beta::x; //declaration ( error) using beta::y; //declaration ( localizes) using beta::z; //declaration ( hides ::Z) X++; // local X Y++; // beta::y Z++; // beta::z... Aliases namespace alias-name = namespace-id ; namespace beta int X, Y,Z; namespace delta float X,Y,Z; int Z; // global Z namespace D = beta::delta; //alias declarations int main() int X = 0; // local X using namespace beta; //directive X++; // local X beta::x++; // X in beta Y++; // beta::y using D::Z; //declaration ( hides ::Z and beta::z) Y++; // beta::y Z++; // beta::delta::z D::X++; // beta::delta::x s (More Rules) Data definitions in namespaces If data definitions are intended to be made public (bad practice!), they must be declared extern in the header file and then defined in the implementation file. Data definitions of a primitive type can be defined with initializers in the implementation file. Data definitions of a class or struct type whose memory must be allocated at runtime (e.g. dynamic arrays) must be defined as pointer variables and then dynamically allocated and initialized explicitly by a procedure call during execution (you should define a special procedure (or proceduress) that serves as an initializer for the namespace. Object.h s as Single Objects #include AppError.h namespace Object // Declare C++ functions representing methods of the namespace object. // At least one of these function must always be defined to properly initialize // the object s environment before any other method can be called. These // initialization functions serve the same purpose as constructors of a class // type. The default initialization method is declared below. void Initialize(); Object.cpp #include Object.h namespace Object Define encapsulated data members here. Primitive data can be directly initialized. Data members of a Class type may have to be defined as pointers and intialized by the initialization method(s). Special boolean protocol variables may have to be defined to ensure Initialize() method is called before any other methods. void Initialize() Define the bodies of the functions declared in the header file. The bodies are defined using The same syntax you would use for functions in C, but they have direct visibility to all data members defined at the top of the namespace
6 Concordance.h #ifndef _CONCORD #define _CONCORD #include <iostream> #include <fstream> #include "Word.h" #include "Reference.h" namespace Concordance void AddWordRef( Word& Wrd, Reference& Ref); void Output( ostream& fout); #endif #include "Word.h" Client Code #include "Reference.h" #include "Concordance.h" int main() Word aword; Reference aref; Concordance::AddWordRef(aword,aref); Concordance::Output( cout ); s as Single Objects Concordance.cpp #include <list> using std::list; #include "Concordance.h" #include "Entry.h" namespace Concordance list<entry> Contents; void AddWordRef( Word& Wrd, Reference& Ref) for (list<entry>::iterator I = Contents.begin(); I!= Contents.end(); I++) if( Wrd < I->GetKey() ) Contents.insert(I,Entry(Wrd,Ref)); return; if( Wrd == I->GetKey() ) I->AddRef(Ref); return; //for Contents.push_back(Entry(Wrd,Ref)); //AddWordRef void Output( ostream& fout) for(list<entry>::iterator I = Contents.begin(); I!= Contents.end(); I++) I->Output(fout); //Output //Concordance 31 s cont d #include Object.h int main(). Object::Initialize(); // Call Object initialization fn Object::Function1(); // Call Object procedure x = Object::Function2(); // Call Object function 32 Team Development with s Team Development with s SystemX Class One Class Two SubA TeamA SubA TeamA: Ted Sally Fred Contains all and only the information Ted needs to make public (for other teams and/or other team members) Ted.h Ted.cpp #include SubA.h using namespace SubA; #include SubB.h namespace SubA //Ted s Code SubB TeamB SubA.h Main Team1 Contains all public declarations for namespace SubA. This is used by clients of SubA (other teams) as well as members of Team A s: Declaring a Function To add a function to a namespace Declare the function in a namespace grouping namespace john1 void greeting( ); s: Defining a Function To define a function declared in a namespace Define the function in a namespace grouping namespace john1 void greeting( ) cout << "Hello from namespace john1.\n"; 35 36
7 s: Using a Function To use a function defined in a namespace Include the using directive in the program where the namespace is to be used Call the function as the function would normally be called int main( ) using namespace john1; greeting( ); Suppose you have the namespaces below: namespace ns1 A Problem Is there an easier way to use both namespaces considering that my_function is in both? fun1( ); my_function( ); namespace ns2 fun2( ); my_function( ); Using directive's scope Example Qualifying Names Using declarations (not directives) allow us to select individual functions to use from namespaces using ns1::fun1; //makes only fun1 in ns1 available The scope resolution operator identifies a namespace here Means we are using only namespace ns1's version of fun1 If you only want to use the function once, call it like this ns1::fun1( ); Qualifiying Parameter Names To qualify the type of a parameter with a using declaration Use the namespace and the type name int get_number (std::istream input_stream) istream is the istream defined in namespace std If istream is the only name needed from namespace std, then you do not need to use Directive/Declaration (Optional) A using declaration (using std::cout;) makes only one name available from the namespace A using directive makes all the names in the namespace available A Subtle Point (Optional) A using directive potentially introduces a name If ns1 and ns2 both define my_function, using namespace ns1; using namespace ns2; is OK, provided my_function is never used! 41 42
8 A Subtle Point Continued A using declaration introduces a name into your code: no other use of the name can be made using ns1::my_function; using ns2::my_function; is illegal, even if my_function is never used Global or unnamed? Names in the global namespace have global scope (all files) They are available without a qualifier to all the program files Names in the unnamed namespace are local to a compilation unit They are available without a qualifier within the compilation unit Display 9.5 (1/2) Display 9.5 (2/2) Display 9.6 Display 9.7 (1/2) 47 48
9 Display 9.7 (2/2) Display 9.8 (1/2) Display 9.8 (2/2) 51
CSC 330 Object Oriented Design. Namespaces
CSC 330 Object Oriented Design Namespaces 1 Introduction C++ was developed in early 1980s by Bjarne Stroustrup (AT&T). It was formulated by adding object oriented (and other) features to C, and removing
More informationOBJECT ORIENTED PROGRAMMING USING C++
OBJECT ORIENTED PROGRAMMING USING C++ 1 Slide 2 Chapter 9 Separate Compilation and Namespaces Created by David Mann, North Idaho College Slide 3 Overview Separate Compilation (9.1) Namespaces (9.2) Slide
More informationLecture 10. Command line arguments Character handling library void* String manipulation (copying, searching, etc.)
Lecture 10 Class string Namespaces Preprocessor directives Macros Conditional compilation Command line arguments Character handling library void* TNCG18(C++): Lec 10 1 Class string Template class
More informationLecture 9. Introduction
Lecture 9 File Processing Streams Stream I/O template hierarchy Create, update, process files Sequential and random access Formatted and raw processing Namespaces Lec 9 Programming in C++ 1 Storage of
More informationOther Topics. Objectives. In this chapter you ll:
Other Topics 23 Objectives In this chapter you ll: Understand storage classes and storage duration. Use const_cast to temporarily treat a const object as a non-const object. Use mutable members in const
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 informationChapter 15 - C++ As A "Better C"
Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference
More informationProgramming C++ Lecture 6. Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor
Programming C++ Lecture 6 Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor Jennifer.sartor@elis.ugent.be S Friends 2 Friends of Objects S Classes sometimes need friends. S Friends are defined outside
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 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 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 informationFunctions and Recursion
Functions and Recursion 1 Storage Classes Scope Rules Functions with Empty Parameter Lists Inline Functions References and Reference Parameters Default Arguments Unary Scope Resolution Operator Function
More informationOutline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O
Outline EDAF30 Programming in C++ 2. Introduction. More on function calls and types. Sven Gestegård Robertz Computer Science, LTH 2018 1 Function calls and parameter passing 2 Pointers, arrays, and references
More informationDistributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes
Distributed Real-Time Control Systems Lecture 17 C++ Programming Intro to C++ Objects and Classes 1 Bibliography Classical References Covers C++ 11 2 What is C++? A computer language with object oriented
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 informationC++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay
C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming
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 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 informationCOMP322 - Introduction to C++ Lecture 02 - Basics of C++
COMP322 - Introduction to C++ Lecture 02 - Basics of C++ School of Computer Science 16 January 2012 C++ basics - Arithmetic operators Where possible, C++ will automatically convert among the basic types.
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 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 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 informationDr. Md. Humayun Kabir CSE Department, BUET
C++ Dr. Md. Humayun Kabir CSE Department, BUET History of C++ Invented by Bjarne Stroustrup at Bell Lab in 1979 Initially known as C with Classes Classes and Basic Inheritance The name was changed to C++
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 informationInput And Output of C++
Input And Output of C++ Input And Output of C++ Seperating Lines of Output New lines in output Recall: "\n" "newline" A second method: object endl Examples: cout
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 informationThe Notion of a Class and Some Other Key Ideas (contd.) Questions:
The Notion of a Class and Some Other Key Ideas (contd.) Questions: 1 1. WHO IS BIGGER? MR. BIGGER OR MR. BIGGER S LITTLE BABY? Which is bigger? A class or a class s little baby (meaning its subclass)?
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 informationcs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers.
cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... today: language basics: identifiers, data types, operators, type conversions, branching and looping, program structure
More informationStreams. Ali Malik
Streams Ali Malik malikali@stanford.edu Game Plan Recap Purpose of Streams Output Streams Input Streams Stringstream (maybe) Announcements Recap Recap - Hello, world! #include int main() { std::cout
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 informationCSC1322 Object-Oriented Programming Concepts
CSC1322 Object-Oriented Programming Concepts Instructor: Yukong Zhang February 18, 2016 Fundamental Concepts: The following is a summary of the fundamental concepts of object-oriented programming in C++.
More informationFunctions, Arrays & Structs
Functions, Arrays & Structs Unit 1 Chapters 6-7, 11 Function Definitions! Function definition pattern: datatype identifier (parameter1, parameter2,...) { statements... Where a parameter is: datatype identifier
More information1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?
1. Describe History of C++? The C++ programming language has a history going back to 1979, when Bjarne Stroustrup was doing work for his Ph.D. thesis. One of the languages Stroustrup had the opportunity
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 informationFunctions, Arrays & Structs
Functions, Arrays & Structs Unit 1 Chapters 6-7, 11 Function Definitions l Function definition pattern: datatype identifier (parameter1, parameter2,...) { statements... Where a parameter is: datatype identifier
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 informationModule 7 b. -Namespaces -Exceptions handling
Module 7 b -Namespaces -Exceptions handling C++ Namespace Often, a solution to a problem will have groups of related classes and other declarations, such as functions, types, and constants. C++provides
More informationEMBEDDED SYSTEMS PROGRAMMING Language Basics
EMBEDDED SYSTEMS PROGRAMMING 2014-15 Language Basics (PROGRAMMING) LANGUAGES "The tower of Babel" by Pieter Bruegel the Elder Kunsthistorisches Museum, Vienna ABOUT THE LANGUAGES C (1972) Designed to replace
More informationCSCE 110 PROGRAMMING FUNDAMENTALS
CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 2. Overview of C++ Prof. Amr Goneid, AUC 1 Overview of C++ Prof. Amr Goneid, AUC 2 Overview of C++ Historical C++ Basics Some Library
More informationUnderstanding main() function Input/Output Streams
Understanding main() function Input/Output Streams Structure of a program // my first program in C++ #include int main () { cout
More informationPROGRAMMING IN C++ KAUSIK DATTA 18-Oct-2017
PROGRAMMING IN C++ KAUSIK DATTA 18-Oct-2017 Objectives Recap C Differences between C and C++ IO Variable Declaration Standard Library Introduction of C++ Feature : Class Programming in C++ 2 Recap C Built
More informationData Structures using OOP C++ Lecture 3
References: th 1. E Balagurusamy, Object Oriented Programming with C++, 4 edition, McGraw-Hill 2008. 2. Robert L. Kruse and Alexander J. Ryba, Data Structures and Program Design in C++, Prentice-Hall 2000.
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 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 information2 ADT Programming User-defined abstract data types
Preview 2 ADT Programming User-defined abstract data types user-defined data types in C++: classes constructors and destructors const accessor functions, and inline functions special initialization construct
More information엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED
엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED Outline - Function Definitions - Function Prototypes - Data
More informationCS242 COMPUTER PROGRAMMING
CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing
More informationCS2141 Software Development using C/C++ C++ Basics
CS2141 Software Development using C/C++ C++ Basics Integers Basic Types Can be short, long, or just plain int C++ does not define the size of them other than short
More informationQUIZ. What are 3 differences between C and C++ const variables?
QUIZ What are 3 differences between C and C++ const variables? Solution QUIZ Source: http://stackoverflow.com/questions/17349387/scope-of-macros-in-c Solution The C/C++ preprocessor substitutes mechanically,
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 informationChapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016
Chapter 6: User-Defined Functions Objectives In this chapter, you will: Learn about standard (predefined) functions Learn about user-defined functions Examine value-returning functions Construct and use
More informationCSCI 1061U Programming Workshop 2. C++ Basics
CSCI 1061U Programming Workshop 2 C++ Basics 1 Learning Objectives Introduction to C++ Origins, Object-Oriented Programming, Terms Variables, Expressions, and Assignment Statements Console Input/Output
More informationPartha Sarathi Mandal
MA 253: Data Structures Lab with OOP Tutorial 1 http://www.iitg.ernet.in/psm/indexing_ma253/y13/index.html Partha Sarathi Mandal psm@iitg.ernet.in Dept. of Mathematics, IIT Guwahati Reference Books Cormen,
More informationIntroduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language
Introduction C++ widely-used general-purpose programming language procedural and object-oriented support strong support created by Bjarne Stroustrup starting in 1979 based on C Introduction to C++ also
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 informationTrue or False (15 Points)
Name Number True or False (15 Points) 1. (15 pts) Circle T for true and F for false: T F a) Value Returning Functions cannot use reference parameters. T F b) Arguments corresponding to value parameters
More informationWelcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:
Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams
More informationIntroduction to C++ with content from
Introduction to C++ with content from www.cplusplus.com 2 Introduction C++ widely-used general-purpose programming language procedural and object-oriented support strong support created by Bjarne Stroustrup
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 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 informationGlobal & Local Identifiers
Global & Local Identifiers the portions of a program where an identifier is defined (may be used). a variable declared inside a Block. from the Declaration statement to the end of the Block void fun()
More informationnptr = new int; // assigns valid address_of_int value to nptr std::cin >> n; // assigns valid int value to n
Static and Dynamic Memory Allocation In this chapter we review the concepts of array and pointer and the use of the bracket operator for both arrays and pointers. We also review (or introduce) pointer
More informationC Functions. Object created and destroyed within its block auto: default for local variables
1 5 C Functions 5.12 Storage Classes 2 Automatic storage Object created and destroyed within its block auto: default for local variables auto double x, y; Static storage Variables exist for entire program
More informationBasic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces
Basic memory model Using functions Writing functions Basics Prototypes Parameters Return types Functions and memory Names and namespaces When a program runs it requires main memory (RAM) space for Program
More informationC++ As A "Better C" Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.
C++ As A "Better C" Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2013 Fall Outline 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.5
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 informationIntroduction to C++ (Extensions to C)
Introduction to C++ (Extensions to C) C is purely procedural, with no objects, classes or inheritance. C++ is a hybrid of C with OOP! The most significant extensions to C are: much stronger type checking.
More informationFile I/O Christian Schumacher, Info1 D-MAVT 2013
File I/O Christian Schumacher, chschuma@inf.ethz.ch Info1 D-MAVT 2013 Input and Output in C++ Stream objects Formatted output Writing and reading files References General Remarks I/O operations are essential
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 informationLecture 7. Log into Linux New documents posted to course webpage
Lecture 7 Log into Linux New documents posted to course webpage Coding style guideline; part of project grade is following this Homework 4, due on Monday; this is a written assignment Project 1, due next
More informationC++ Quick Guide. Advertisements
C++ Quick Guide Advertisements Previous Page Next Page C++ is a statically typed, compiled, general purpose, case sensitive, free form programming language that supports procedural, object oriented, and
More informationIII. Classes (Chap. 3)
III. Classes III-1 III. Classes (Chap. 3) As we have seen, C++ data types can be classified as: Fundamental (or simple or scalar): A data object of one of these types is a single object. int, double, char,
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 informationCMSC 202 Midterm Exam 1 Fall 2015
1. (15 points) There are six logic or syntax errors in the following program; find five of them. Circle each of the five errors you find and write the line number and correction in the space provided below.
More informationImplementing an ADT with a Class
Implementing an ADT with a Class the header file contains the class definition the source code file normally contains the class s method definitions when using Visual C++ 2012, the source code and the
More informationCS11 Introduction to C++ Fall Lecture 1
CS11 Introduction to C++ Fall 2006-2007 Lecture 1 Welcome! 8 Lectures (~1 hour) Slides posted on CS11 website http://www.cs.caltech.edu/courses/cs11 7 Lab Assignments on course website Available on Monday
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 informationCSC 211 Intermediate Programming. Arrays & Pointers
CSC 211 Intermediate Programming Arrays & Pointers 1 Definition An array a consecutive group of memory locations that all have the same name and the same type. To create an array we use a declaration statement.
More informationCh 2 ADTs and C++ Classes
Ch 2 ADTs and C++ Classes Object Oriented Programming & Design Constructing Objects Hiding the Implementation Objects as Arguments and Return Values Operator Overloading 1 Object-Oriented Programming &
More informationC++ basics Getting started with, and Data Types.
C++ basics Getting started with, and Data Types pm_jat@daiict.ac.in Recap Last Lecture We talked about Variables - Variables, their binding to type, storage etc., Categorization based on storage binding
More informationTutorial-2a: First steps with C++ programming
Programming for Scientists Tutorial 2a 1 / 18 HTTP://WWW.HEP.LU.SE/COURSES/MNXB01 Introduction to Programming and Computing for Scientists Tutorial-2a: First steps with C++ programming Programming for
More informationOperator Overloading in C++ Systems Programming
Operator Overloading in C++ Systems Programming Operator Overloading Fundamentals of Operator Overloading Restrictions on Operator Overloading Operator Functions as Class Members vs. Global Functions Overloading
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 informationWelcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:
Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams
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 information1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.
1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol. B. Outputs to the console a floating point number f1 in scientific format
More informationFORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam I: True (A)/False(B) (2 pts each):
FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam I: True (A)/False(B) (2 pts each): 1. The basic commands that a computer performs are input (get data), output (display result),
More information5. Assuming gooddata is a Boolean variable, the following two tests are logically equivalent. if (gooddata == false) if (!
FORM 2 (Please put your name and form # on the scantron!!!!) CS 161 Exam I: True (A)/False(B) (2 pts each): 1. Assume that all variables are properly declared. The following for loop executes 20 times.
More informationSRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR
SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR 603203 DEPARTMENT OF COMPUTER SCIENCE & APPLICATIONS QUESTION BANK (2017-2018) Course / Branch : M.Sc CST Semester / Year : EVEN / II Subject Name
More informationComputing and Statistical Data Analysis Lecture 3
Computing and Statistical Data Analysis Lecture 3 Type casting: static_cast, etc. Basic mathematical functions More i/o: formatting tricks Scope, namspaces Functions 1 Type casting Often we need to interpret
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 informationPIC 10A Objects/Classes
PIC 10A Objects/Classes Ernest Ryu UCLA Mathematics Last edited: November 13, 2017 User-defined types In C++, we can define our own custom types. Object is synonymous to variable, and class is synonymous
More informationTrue or False (14 Points)
Name Number True or False (14 Points) 1. (15 pts) Circle T for true and F for false: T F a) void functions can use the statement return; T F b) Arguments corresponding to value parameters can be variables.
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 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 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 informationOperator overloading
1 Introduction 2 The copy constructor 3 Operator Overloading 4 Eg 1: Adding two vectors 5 The -> operator 6 The this pointer 7 Overloading = 8 Unary operators 9 Overloading for the matrix class 10 The
More informationSFU CMPT Topic: Classes
SFU CMPT-212 2008-1 1 Topic: Classes SFU CMPT-212 2008-1 Topic: Classes Ján Maňuch E-mail: jmanuch@sfu.ca Friday 15 th February, 2008 SFU CMPT-212 2008-1 2 Topic: Classes Encapsulation Using global variables
More informationClasses, Constructors, etc., in C++
Classes, Constructors, etc., in 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
More information