





































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
this is c programing notes
Typology: Study notes
1 / 77
This page cannot be seen from the preview
Don't miss anything!






































































VFR November, 03^
SE2B2 Further Computer Systems
C^ REATING AND USING A COPY CONSTRUCTOR
........................................................................................ 27
STRUCTURE OF THE COURSE .........................................................................................................
USING DEFAULT ARGUMENTS
.................................................................................................................. 29
GENERALITY^ ...............................................................................................................................................
OVERLOADING AND AMBIGUITY
.............................................................................................................. 30
S^ IMPLE OBJECTS^ ..........................................................................................................................................
F^ INDING THE ADDRESS OF AN OVERLOADED FUNCTION
.......................................................................... 30
DERIVED^ C^ LASSES^ ......................................................................................................................................3 TEMPLATES^ .................................................................................................................................................
OPERATOR OVERLOADING........................................................................................................... 31
S^ TREAMS^ .....................................................................................................................................................
THE BASICS OF OPERATOR OVERLOADING
............................................................................................... 31 OVERLOADING BINARY OPERATORS
........................................................................................................ 32
C++ BOOKS .............................................................................................................................................
OVERLOADING THE RELATIONAL AND LOGICAL OPERATORS
................................................................. 34
F^ OR^ WINDOWS^ :........................................................................................
Error! Bookmark not defined.
OVERLOADING A UNARY OPERATOR
....................................................................................................... 34 USING FRIEND OPERATOR FUNCTIONS
..................................................................................................... 35
GENERALITY .........................................................................................................................................
A^ CLOSER LOOK AT THE ASSIGNMENT OPERATOR
................................................................................... 37
AN OVERVIEW OF^ C++................................................................................................................................
OVERLOADING THE^ [ ]^ SUBSCRIPT OPERATOR
......................................................................................... 38
OBJECT^ ORIENTED^ P^ ROGRAMMING
(OOP) ................................................................................................ DIFFERENCES BETWEEN^ C
AND^ C++ ..........................................................................................................
INHERITANCE..................................................................................................................................... 39
DIFFERENCES BETWEEN^ C++
AND^ S^ TANDARD^ C++ ..................................................................................
B^ ASE CLASS ACCESS CONTROL
................................................................................................................ 39 USING PROTECTED MEMBERS
.................................................................................................................. 40
C++ CONSOLE I/O .................................................................................................................................
C^ ONSTRUCTORS^ ,^ DESTRUCTORS
,^ AND INHERITANCE^ .............................................................................. 41
C AND C++ COMMENTS......................................................................................................................
MULTIPLE INHERITANCE .......................................................................................................................... 43 VIRTUAL BASE CLASSES^ ........................................................................................................................... 45
CLASSES ..................................................................................................................................................
VIRTUAL FUNCTIONS ...................................................................................................................... 46
FUNCTION OVERLOADING: AN INTRODUCTION .....................................................................
P^ OINTERS TO DERIVED CLASS
.................................................................................................................. 46 INTRODUCTION TO VIRTUAL FUNCTIONS
................................................................................................. 47
CONSTRUCTORS AND DESTRUCTORS FUNCTIONS ...............................................................
MORE ABOUT VIRTUAL FUNCTIONS
......................................................................................................... 49
C^ ONSTRUCTORS^ ........................................................................................................................................
APPLYING POLYMORPHISM
...................................................................................................................... 51
DESTRUCTORS^ ..........................................................................................................................................10 C^ ONSTRUCTORS THAT TAKE PARAMETERS
..............................................................................................
C++ I/O SYSTEM.................................................................................................................................. 53 S^ OME^ C++ I/O^ BASICS^ ............................................................................................................................. 53
INHERITANCE: AN INTRODUCTION ............................................................................................
C^ REATING YOUR OWN INSERTERS
........................................................................................................... 54
OBJECT POINTERS ............................................................................................................................
C^ REATING EXTRACTORS^
.......................................................................................................................... 55 MORE^ C++ I/O B^ ASICS^ ............................................................................................................................ 56
IN-LINE FUNCTIONS..........................................................................................................................
F^ ORMATTED^ I/O....................................................................................................................................... 57
AUTOMATIC IN^ - LINING^ .............................................................................................................................
USING WIDTH^ ( ),^ PRECISION
( ),^ AND FILL^ ( )............................................................................................. 58 USING^ I/O^ MANIPULATORS
...................................................................................................................... 59
MORE ABOUT CLASSES ...................................................................................................................14 ASSIGNING OBJECT^ ...................................................................................................................................
ADVANCE C++ I/O .............................................................................................................................. 60
P^ ASSING OBJECT TO FUNCTIONS
...............................................................................................................
C^ REATING YOUR OWN MANIPULATORS
................................................................................................... 60
R^ ETURNING OBJECT FROM FUNCTIONS
.....................................................................................................
F^ ILE^ I/O^ BASICS........................................................................................................................................ 60
F^ RIEND FUNCTIONS:^ AN INTRODUCTION
..................................................................................................
UNFORMATTED^ ,^ BINARY I/O ................................................................................................................... 63 MORE UNFORMATTED^ I/O
FUNCTIONS^ .................................................................................................... 64
ARRAYS, POINTERS, AND REFERENCES ....................................................................................
R^ ANDOM ACCESS^ ..................................................................................................................................... 65
ARRAYS OF OBJECTS^ .................................................................................................................................
C^ HECKING THE^ I/O^ STATUS
..................................................................................................................... 66
USING POINTERS TO OBJECTS
...................................................................................................................
C^ USTOMISED^ I/O^ AND FILES
.................................................................................................................... 67
THE^ THIS^ POINTER^ ...................................................................................................................................20 USING^ NEW^ AND^ DELETE......................................................................................................................
TEMPLATES AND EXCEPTION HANDLING............................................................................... 68
MORE ABOUT NEW AND DELETE
...............................................................................................................
GENERIC FUNCTIONS^ ................................................................................................................................ 68
R^ EFERENCES^ .............................................................................................................................................
GENERIC CLASSES^ .................................................................................................................................... 70
P^ ASSING REFERENCES TO OBJECTS
...........................................................................................................
EXCEPTION HANDLING^ ............................................................................................................................. 72
R^ ETURNING REFERENCES
.........................................................................................................................
MORE ABOUT EXCEPTION HANDLING
...................................................................................................... 74 HANDLING EXCEPTIONS THROWN BY NEW
.............................................................................................. 76
INDEPENDENT REFERENCES AND RESTRICTIONS
...................................................................................... FUNCTION OVERLOADING.............................................................................................................25 OVERLOADING CONSTRUCTOR FUNCTIONS
.............................................................................................. Standard C++ programming
VFR November, 03^
SE2B2 Further Computer Systems
GENERALITY An overview of C++ C++ is the object oriented extension of C. As for C there is an ANSI/ISOstandard ( final draft 1998) for the C++ programming language. This will ensurethat the C++ code is portable between computers. The C++ programming language teach here is the Standard C++. This is theversion^ of^ C++^ created
Object Oriented Programming (OOP) Although structured programming has yielded excellent results when applied tomoderately complex programs, even it fails at some point, after a program reachesa certain size. To allow more complex programs to be written, object-orientedprogramming has been invented. OOP takes the best of the ideas in structuredprogramming and combines them with powerful new concepts that allow you toorganise your programme more efficiently. Object oriented programming encourage you to decompose a problem into itsconstituent parts. Each^ component^
instructions and data that relate to that object. In this way, complexity is reducedand the programmer can manage larger program. All OOP languages, including C++, share three common defining traits. Encapsulation Encapsulation^ is^ the
Standard C++ programming
VFR November, 03^
SE2B2 Further Computer Systems
An object is a variable of a user-defined type. Each time you define a new type ofobject, you are creating a new data type. Each specific instance of this data type isa compound variable. Polymorphism Polymorphism is the quality that allows one name to be used for two or morerelated but technically different purposes. Polymorphism allows one name to specify a general class of actions. Within ageneral class of actions, the specific action to be applied is determined by the typeof data. For example, in C, the absolute value action requires three distinctfunction names:^ a b s ( )
overloading. More generally the concept of polymorphism is characterised by the idea ‘oneinterface, multiple methods’. The key point to remember about polymorphism isthat it allows you to handle greater complexity by allowing the creation ofstandard interfaces to related activities. Inheritance Inheritance is the process by which one object can acquire the properties ofanother. An object can inherit a general set of properties to which it can add thosefeatures that are specific only to itself. Inheritance is important because it allows an object to support the concept of hierarchical classification.
classification. The child class inherits all those qualities associated with the parent and adds tothem its own defining characteristics. Differences between C and C++ Although C++ is a subset of C, there are some small differences between the two,and few are worth knowing from the start. First, in C, when a function takes no parameters, its prototype has the word
// C++ version
Standard C++ programming
VFR November, 03^
SE2B2 Further Computer Systems
using namespace std
; C++ CONSOLE^ I/O
using namespace
std; int^ main ( ) {^ //^ local variables^ int^ i;^ float^ f;^ //^ program code^ cout^ <<^ "Enter an integer then a float ";^ //
no automatic newline cin >> i >> f;^ //^ input an integer and a float
cout^ <<^ "i= " << i
<<^ " f= "^ <<^ f
<<^ "\n"; //^ output i then f and newline return 0; }
C^ AND^ C++ C
OMMENTS /*^ This is a C-like comment.^ The program determines whether^ an integer is odd or even. */ #include^ <^ iostream
using namespace
std; int^ main ( ) {^ int^ num;^ //
This is a C++ single-line comment. // read the number cout << "Enter number to be tested: "; cin >> num; // see if even or odd if ((num%2)==0)^ cout <<^ "Number is even\n"; else cout << "Number is odd\n"; return 0;
//^ is nested a single-line comment
Here is the end of the multiline comment. */
Standard C++ programming
VFR November, 03^
SE2B2 Further Computer Systems
CLASSES
{ // private functions and variables public: // public functions and variables
iostream^ > using namespace^ std; // class declaration class myclass^ { // private members to myclass int a; public: // public members to myclass void set_a( int^ num); int get_a( ); };
int^ num) {
:: func-name ( parameter- list
these are object of type myclass
Standard C++ programming
8
VFR November, 03^
SE2B2 Further Computer Systems
//^ abs( ) for double double^ abs ( double
n) { cout << "In double abs( )\n"; return n<0? -n : n;
a); double f1 ( int^ a); ... f1(10); // which function does the compiler call??? CONSTRUCTORS AND^ DESTRUCTORS
FUNCTIONS Constructors When applied to real problems, virtually every object you create will requiresome sort of initialisation. C++ allows a
iostream^ > using namespace^ std; // class declaration class myclass^ { int a; public:
myclass(^ );^ //
constructor void^ show( ); }; myclass::myclass( ) { cout <<^ "In constructor\n"; a=10; } myclass::show( ) { cout^ << a; } int main ( ) { int^ ob; //^ automatic call to constructor ob.show( ); return^ 0; } In this simple example the constructor is called when the object is created, and theconstructor initialises the private variable a to 10. For a global object, its constructor is called once, when the program first beginsexecution. For local objects, the constructor is called each time the declaration statement isexecuted. Destructors The complement of a constructor is the
#include^ <^ iostream
using namespace
std; //^ class declaration class^ myclass^ {^ int^ a;^ public:^ myclass(^ );
// constructor ∼myclass( );^ // destructor void show( ); }; myclass::myclass( ) {^ cout <<^ "In constructor\n";
Standard C++ programming
VFR November, 03^
SE2B2 Further Computer Systems
programming style and should be avoided. Constructors that take parameters It is possible to pass one or more arguments to a constructor function. Simply addthe^ appropriate^ parameters
iostream^ > using namespace^ std; // class declaration class myclass^ { int a; public: myclass( int^ x); // constructor void show( ); }; myclass::myclass( int^ x) { cout << "In constructor\n"; a=x; } void myclass::show( ) { cout << a <<"\n"; } int main ( ) { myclass ob(4); ob.show( );
Although the previous example has used a constant value, you can pass anobject’s constructor any valid expression, including variables.^ I^ NHERITANCE
:^ AN INTRODUCTION
i; public: void set_i( int^ n); int get_i( ); };
Standard C++ programming
VFR November, 03^
SE2B2 Further Computer Systems
OBJECT POINTERS
iostream^ > using namespace^ std; class myclass { int a; public: myclass( int^ x);^ //
constructor int^ get( ); }; myclass :: myclass( int
x) { a=x; } int^ myclass :: get( ) { return^ a; } int main ( ) {^ myclass ob(120);
// create object myclass^ ***** p;^
// create pointer to object p= & ob;^ //
put address of ob into p cout <<^ "value using object: "
<<^ ob. get( ); cout^ <<^ "\n"; cout <<^ "value using pointer: "
<<^ p -> get( ); return^ 0;
I^ N-^ LINE FUNCTIONS
iostream^ > using namespace^ std; inline int even( int^ x) { return^ !(x%2); } int main ( ) { if (even(10))^ cout <<
"10 is even\n";
Standard C++ programming
VFR November, 03^
SE2B2 Further Computer Systems
if^ (even(11))^ cout <<
"11 is even\n";
cout <<^ "10 is even\n";
cout <<^ "10 is even\n";
Depending upon the compiler, several restrictions to in-line functions may apply.If any in-line restriction is violated the compiler is free to generate a normalfunction. Automatic in-lining If a member function’s definition is short enough, the definition can be includedinside the class declaration. Doing so causes the function to automatically becomean in-line function, if possible. When a function is defined within a classdeclaration, the^ inline
iostream^ > using namespace^ std; class samp { int i, j; public: samp(int a, int b); // divisible is defined here and // automatically in-lined int divisible( ) { return !(i%j); } }; samp :: samp(int a, int b){ i = a; j = b; }
int main ( ) {^ samp ob1(10, 2), ob2(10, 3);^ // this is true^ if (ob1.divisible( ))
cout<<^ "10 divisible by 2\n"; // this is false if^ (ob2.divisible( ))
cout <<^ "10 divisible by 3\n"; return^ 0; } Perhaps the most common use of in-line functions defined within a class is todefine constructor and destructor functions. The samp class can more efficientlybe defined like this: //... class^ samp {^ int^ i, j; public:^ // inline constructor^ samp(int a, int b) { i = a; j = b; }^ int^ divisible( ) { return !(i%j); } }; //...^ MORE ABOUT CLASSES Assigning object One object can be assigned to another provided that both are of the same type. Bydefault, when one object is assigned to another, a bitwise copy of all the datamembers is made. For example, when an object called
Standard C++ programming
VFR November, 03^
SE2B2 Further Computer Systems
//^ Set o.i to its square. //^ This affect the calling argument void^ sqr_it(samp o) {^ o->set(o->get_i( )o->get_i( )); } // ... int main ( ) {^ samp a(10);^ sqr_it(&a);
//^ pass a’s address to sqr_it
which we will see later on. Returning object from functions Functions can return objects. First, declare the function as returning a class type.Second, return an object of that type using the normal
char^ s[80]; public: void^ show( ) {^
cout^ << s << "\n"; } void^ set( char^ *str) {
strcpy (s, str); } }; // Return an object of type samp samp^ input( ) {^ char^ s[80];^ samp^ str;^ cout^ << "Enter a string: ";^ cin^ >> s;^ str.set(s);^ return^ str; } int main ( ) {^ samp ob;^ // assign returned object to ob^ ob = input( );^ ob.show( );^ return^ 0; } Friend functions: an introduction There will be time when you want a function to have access to the privatemembers of a class without that function actually being a member of that class.Towards this, C++ supports friend functions. A friend function is not a memberof a class but still has access to its private elements. Friend functions are useful with operator overloading and the creation of certaintypes of I/O functions. A friend function is defined as a regular, nonmember function. However, insidethe class declaration for which it will be a friend, its prototype is also included,prefaced by the keyword^
n, d; public: myclass( int^ i,^ int^
j) { n = i; d = j; } // declare a friend of myclass
Standard C++ programming
VFR November, 03^
SE2B2 Further Computer Systems
friend int^ isfactor(myclass ob); }; /* Here is friend function definition. It returns true if d is a factor of n. Notice that the keyword friend is not used in the definition of isfactor( ). */ int isfactor(myclass ob) { if^ ( !(ob.n % ob.d) )
return^ 1; else return^ 0; } int main ( ) { myclass ob1(10, 2), ob2(13, 3); if (isfactor(ob1))
cout^ << "2 is a factor of 10\n";^ else cout
<< "2 is not a factor of 10\n"; if (isfactor(ob2))^ cout^ << "3 is a factor of 13\n";^ else cout
<< "3 is not a factor of 13\n"; return 0;
// wrong isfactor is not a member^ // function
class^ truck;^ //
This is a forward declaration class^ car {^ int^ passengers;^ int^ speed;^ public:^ car( int^ p,
int^ s) { passengers = p; speed =s; } friend int sp_greater(car c, truck t); }; class^ truck {^ int^ weight;^ int^ speed;^ public:^ truck( int^
w,^ int^ s) { weight = w; speed = s; } friend int sp_greater(car c, truck t);
forward declaration class^ car {^ int^ passengers;^ int^ speed;^ public:^ car( int^ p,
int^ s) { passengers = p; speed =s; } int sp_greater( truck t); }; class^ truck {^ int^ weight;^ int^ speed;
Standard C++ programming
17
VFR November, 03^
SE2B2 Further Computer Systems
a; public: samp( int^ n) {a = n; } int get_a( ) {^ return
a; } }; int main ( ) {^ samp ob[4][2] = {
int^ i; for^ (i=0; i<4; i++)
cout^ << ob[i][0].get_a( ) << "
a; } int^ get_b( ) {^
return^ b; } }; int main ( ) {^ samp ob[4][2] = {
samp(1, 2), samp(3, 4),
samp(5, 6), samp(7, 8), samp(9, 10), samp(11, 12), samp(13, 14), samp(15, 16) }; // ... Note you can always the long form of initialisation even if the object takes onlyone argument. It is just that the short form is more convenient in this case. Using pointers to objects As you know, when a pointer is used, the object’s members are referenced usingthe arrow (- >) operator instead of the dot (.) operator. Pointer arithmetic using an object pointer is the same as it is for any other datatype: it is performed relative to the type of the object. For example, when anobject pointer is incremented, it points to the next object. When an object pointeris decremented, it points to the previous object. //^ Pointer to objects // ... class^ samp {^ int^ a, b;^ public:^ samp( int^ n,
int^ m) {a = n; b = m; } int get_a( ) {^ return^ a; } int get_b( ) {^ return^ b; } }; int main ( ) {^ samp ob[4] = {
samp(1, 2), samp(3, 4), samp(5, 6), samp(7, 8) }; int^ i; samp *p; p = ob;^ //^ get starting address of array for^ (i=0; i<4; i++) {^ cout^ << p->get_a( ) << "
cout^ << p->get_b( ) << "\n"; p++;^ //^ advance to next object } // ...
Standard C++ programming
VFR November, 03^
SE2B2 Further Computer Systems
The THIS pointer C++ contains a special pointer that is called
//^ assume that ob is an object
//^ Demonstrate the this pointer # include^ <^ iostream
using namespace
std; class^ inventory {^ char^ item[20];^ double^ cost;^ int^ on_hand;^ public:^ inventory(
char^ *i,^ double
c,^ int^ o) { // access members through // the this pointer strcpy ( this ->item, i); this ->cost = c; this ->on_hand = o; } void^ show( ); }; void inventory::show( ) { cout^ <<^ this ->item;
// use this to access members cout^ << ": £" <<
this ->cost; cout^ << "On hand: " <<
this ->on_hand <<"\n";
In fact the first form is a shorthand for the second. Though the second form isusually not used for such simple case, it helps understand what the shorthandimplies. The^ this^ pointer has several uses, including aiding in overloading operators (seelater). By default, all member functions are automatically passed a pointer to theinvoking object. Using NEW and DELETE When memory needed to be allocated, you have been using
p-var^ =^ new^ type
Standard C++ programming
20