85
Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

C cpluplus 2

Embed Size (px)

Citation preview

Page 1: C cpluplus 2

Introduction to C++ Programming

Csci 169

Prof.A.Bellaachia

And

Anasse Bari

Page 2: C cpluplus 2

Agenda Session 1

1. A Historical Perspective of C++

2. Major Differences between C and C++

3. Basics of C++

Structure of a program

Variables and Data types

Constants

Operators

Basic Input / output

4. Control Structures

Structures

Functions

5. Compound Data Types

Arrays

Characters

Pointers

Dynamic Memory

6. C++ and Object Oriented Programming

Classes

Objects

Constructors

Overloaded Constructors

Destructor

Copy Constructor

Inheritance ( Public and Private)

Function Overloading

Operator Overloading

Access Control

Friendship

Virtual Functions

Polymorphism

Page 3: C cpluplus 2

C++ : Historical Perspective

• What is C++ ?

• Who invented C++ ?

• Who are the users of C++ ?

Page 4: C cpluplus 2

C and C++

• C is a Procedural Language :

“Decide which procedures you want; use the best algorithms you can find”

• C++ is an Object Oriented Language:

“Decide which modules you want; partition the program so that data is hidden within modules”

• C was chosen to be the base of C++ because:

1.C is versatile and terse

2.C is adequate for most systems programming tasks

3.C runs everywhere and on everything

Page 5: C cpluplus 2

Basics of C++

• Structure of a C++ program

• Variables and Data types

• Constants

• Operators

• Basic Input / output

Page 6: C cpluplus 2

Our First C++ Program// my first program in C++

#include <iostream.h>

Using namespace std;

int main ()

{

cout << “Hello Cs169 / Fall 2009 Students“;

return 0;

}

Page 7: C cpluplus 2

7

Structure of a C++ Program

/* greeting.cpp greets its user.** Input: The name of the user* Output: A personalized greeting*********************************************************/#include <iostream> // cin, cout, <<, >>#include <string> // stringusing namespace std;int main(){cout << "Please enter your first name: ";string firstName;cin >> firstName;cout << "\nWelcome to the world of C++, " << firstName << "!\n";}

Comment

Compilerdirectives

Specifies standard related names

Main portion of program.

Contains C++ statements.

Page 8: C cpluplus 2

Variables and Data Types

• Variable : a portion of memory to store a determined value.

• How to distinguish variables ? Identifiers

• Identifiers:

– Combination of letters, digits, and underscores

– Variable names should start with letter or digit

• Important : C++ is a “case sensitive” language

Page 9: C cpluplus 2

Fundamental DataTypes

Page 10: C cpluplus 2

More on Variables

• Declaration – – int number1;– float number2;

• Initialization –– int number1 = 0;– int number2 = 3.3;

• Assignment-– number1=5;– number2=number1;

Page 11: C cpluplus 2

Scope of Variables

• Global Variables – variables that are declared above main() can be accessed anywhere after the declaration

• Local Variables – variables declared in section of code {}. Only accessible in that region.

Page 12: C cpluplus 2

Scope of Variables

Page 13: C cpluplus 2

Initialization of Variables

Two possibilities:

• type identifier = initial_value ;

• type identifier (initial_value) ;

Page 14: C cpluplus 2

Initialization of Variables// initialization of variables

#include <iostream.h>

Using namespace std;

int main ()

{

int x=5;

int y(2);

int result;

x = x + 3;

result = x - y

cout << result;

return 0;

}

Page 15: C cpluplus 2

Characters and Strings

• ‘X’ is a character• “hello Cs169-Fall2009” is a string• C++ library provides support for strings : string class

string mystring = "This is a string"; string mystring ("This is a string");

Page 16: C cpluplus 2

Strings Example

// my first string

#include <iostream>

#include <string>

using namespace std;

int main () {

string mystring;

mystring = “Hello Cs169, Fall 2009";

cout << mystring << endl;

mystring = “Hello Cs169, I wish you a great semester";

cout << mystring << endl;

return 0;

}

.

Page 17: C cpluplus 2

Defined Constants

• #define identifier value

#define PI 3.14159265 Example: Write a program that calculates the area and

circumference of a Circle of Radius 10.

Page 18: C cpluplus 2

Declared Constants (const)

• Use the “const” prefix you can declare constant with specific type

Examples:

– const int radius = 100;

– const char tabulator = '\t';

Page 19: C cpluplus 2

Arithmetic OperatorsAssignment Operator ( = ) // assignment operator

#include <iostream>

using namespace std;

int main ()

{

int a, b; // a:?, b:?

a = 10; // a:10, b:?

b = 4; // a:10, b:4

a = b; // a:4, b:4

b = 7; // a:4, b:7

cout << "a:";

cout << a;

cout << " b:";

cout << b;

return 0;

}

Page 20: C cpluplus 2

Arithmetic Operators Compound assignment

Increment & Decrement ( ++,--)

Relational and equality operators ( ==, !=, >, <, >=, <= )

Page 21: C cpluplus 2

Arithmetic Operators Logical Operators ( !, &&, || )

Page 22: C cpluplus 2

Arithmetic Operators

• + addition

• - subraction

• * multiplication

• / division

• % modulo or remainder

Page 23: C cpluplus 2

Basic C++ I/O• “iostream” C++ library• Cout

cout << “Hello Cs169”; //Print Hello Cs169

cout << 120; // Print 120 on the screen

cout << x; // print the content of x in the screen• Cin

int age;

cin >> age;

cout << age

cin >> a >> b; is equivalent to cin>>a; cin>>b;

Page 24: C cpluplus 2

Agenda Session 1

1. A Historical Perspective of C++

2. Major Differences between C and C++

3. Basics of C++

Structure of a program

Variables and Data types

Constants

Operators

Basic Input / output

4. Control Structures

Structures

Functions

5. Compound Data Types

Arrays

Characters

Pointers

Dynamic Memory

6. C++ and Object Oriented Programming

Classes

Friendship and Inheritance

Polymorphism

Page 25: C cpluplus 2

Control structures

• if (cond) state1 else if (cond2) state2 else state3• while (expression) statement• do statement while (cond)• for (init; cond; increment) statement;

Page 26: C cpluplus 2

Control structuresExample

Page 27: C cpluplus 2

Control structuresExample

Page 28: C cpluplus 2

Switch Statement

switch (x) { \

case 1:

cout << "x is 1";

break;

case 2:

cout << "x is 2";

break;

default:

cout << "value of x unknown";

}

Page 29: C cpluplus 2

Functions

• We can use functions to achieve structured programmingInt add(int a, int b){

a = a+b; return (a);

}

• ‘int’ is the return type, ‘a’ and ‘b’ are arguments• When we call the function we must pass it

parameters matching the arguments

Page 30: C cpluplus 2

FunctionsExample

Page 31: C cpluplus 2

Passing Parameters

• Call By Value– This is what we usually do, we pass a function

the value of a variable

• Call By Reference– Instead of the value we will pass a pointer to

the variable. If we modify the passed variable the change will be seen by the caller

– We use ‘&parm’ to show that we are passing the variable at the memory location of parm

Page 32: C cpluplus 2

Agenda Session 1

1. A Historical Perspective of C++

2. Major Differences between C and C++

3. Basics of C++

Structure of a program

Variables and Data types

Constants

Operators

Basic Input / output

4. Control Structures

Structures

Functions

5. Compound Data Types

Arrays

Characters

Pointers

Dynamic Memory

6. C++ and Object Oriented Programming

Classes

Friendship and Inheritance

Polymorphism

Page 33: C cpluplus 2

Arrays

• An Array is a set of elements of the same type located in contiguous memory locations.

• An Array can be referenced using index

Page 34: C cpluplus 2

Arrays

• Intialization– int numbers[5]={0,1,2,3,4,};

• Accessing– num2 =numbers[1];– numbers[0]=99;

• Passing arrays as parameters– Declaration: int add(int numarray[])– Call:

int array[]={1,2,3};add(array);

Page 35: C cpluplus 2

ArraysExample

Page 36: C cpluplus 2

Pointers

• We used pointers in call by reference

• A reference of a variable is the address that locates a variable in Memory

• Pointer are Valuable in implementing data structures

Page 37: C cpluplus 2

Address Operator (&)

• The ‘&’ operator returns the ‘address of’ its operand.

• ‘&’ can be translated ‘address of’

Page 38: C cpluplus 2

Dereference Operator (*)(*) “Values pointed by”

• Notice the difference:

& is the reference operator and can be read as "address of"

* is the dereference operator and can be read as "value pointed by”

Page 39: C cpluplus 2

PointersExample

Page 40: C cpluplus 2

Sizeof()

• The Sizeof() function is used to determine how many bytes of a data type during compilation.

• Ex:sizeof(float) equals 4

float array[10];

sizeof(array) equals 4*10 which is40

Page 41: C cpluplus 2

Dynamic Memory

• Dynamic Memory allows us to determine and allocate memory to variables and data structures at ‘run time’.

• C++ uses new and delete;– pointer = new type;

• New returns a pointer to the allocated memory

– delete pointer;• Frees up the memory that was allocated

Page 42: C cpluplus 2

Dynamic MemoryExample

Page 43: C cpluplus 2

Structs

• Similar to records in Ada.struct person_t{

char fname[20];char lname[20];int age;

}person1, person2;

• Here we are declaring person1 and person2 as type person_t.

• By convention we use the _t

Page 44: C cpluplus 2

Accessing the struct members

• We use the ‘.’ to access members of a structcout << person1.fname;

person1.fname=“John”;

Page 45: C cpluplus 2

StructsExample

Page 46: C cpluplus 2

Pointers to Structs

• We can point to a struct like other structures.Person_t* person1Ptr;

person1Ptr = &person1;

• We can no longer use the ‘.’ to access the members in the struct we are pointing to.– The ‘->’ is used

Cout << person1Ptr->fname;

– Element fname of structed pointed by person1Ptr

– Same as *(person1Ptr.fname);

Page 47: C cpluplus 2

Agenda Session 1

1. A Historical Perspective of C++

2. Major Differences between C and C++

3. Basics of C++

Structure of a program

Variables and Data types

Constants

Operators

Basic Input / output

4. Control Structures

Structures

Functions

5. Compound Data Types

Arrays

Characters

Pointers

Dynamic Memory

6. C++ and Object Oriented Programming

Classes

Objects

Constructors

Overloaded Constructors

Destructor

Copy Constructor

Inheritance ( Public and Private)

Function Overloading

Operator Overloading

Access Control

Friendship

Polymorphism

Page 48: C cpluplus 2

C++ Classes

• A Class is User-defined type

• An Object is an instance of a Class

• A Class has : – Members Variables

– Member Functions

– Constructor

– Destructor

Page 49: C cpluplus 2

C++ ClassesExample

Page 50: C cpluplus 2

Constructors

• A Constructor is a member function that initializes an Object of a Class

• A Constructor has the same name as the class it belongs to

• A Constructor can be overloaded

• The compiler select the correct one for each use

Good Practices:

• Always define a constructor and always initialize all data members

• If you do not create a constructor one is automatically defined (not recommended

• Warning: attempting to initialize a data member of a class explicitly without using a constructors is a syntax error.

.

Page 51: C cpluplus 2

ConstructorsExample

Class Date {

int d,m,y

Public:

//…

Date(int,int,int) //day,month, year

Date(int,int) //day, month, today’s year

Date(int) //day, today’s month and year

Date(); //default Date

Date(char*) // date in string representation

}

Date today(4);

Date july4(“july 4,1983)

Date guy(“5 nov”)

Date now;

Page 52: C cpluplus 2

Destructors• It is a member function which deletes an object.• A destructor function is called automatically when the

object goes out of scope: (1) the function ends (2) the program ends (3) a block containing temporary variables ends (4) a delete operator is called 

• A destructor has: (i) the same name as the class but is preceded by a tilde

(~) (ii) no arguments and return no values

Page 53: C cpluplus 2

Destructors

• It is a member function which deletes an object.• A destructor function is called automatically when the

object goes out of scope. e.g. a block containing temporary variables ends

• A destructor has the same name as the class but is preceded by a tilde (~)

• A Destructor has no arguments and return no values

Page 54: C cpluplus 2

DestructorsExample

class mystring { private: char *str; int s; //size public: mystring(char *); // constructor ~mystring(); // destructor}; mystring::mystring(char *c){ size = strlen(c); str = new char[s+1]; strcpy(s,c);} mystring::~mystring(){ delete []str;}

Page 55: C cpluplus 2

Copy Constructor

• A member function which initializes an object using another object of the same class.

• Copy constructor prototype

myclass (const myname&);

Page 56: C cpluplus 2

class myrectangle { private: float height; float width; int x; int y; public: rectangle(float, float); // constructor rectangle(const myrectangle&); // copy constructor void draw(); // draw member function void posn(int, int); // position member function void move(int, int); // move member function};

Copy ConstructorExample

Page 57: C cpluplus 2

Importance of a copy constructors

• In the absence of a copy constructor, the C++ compiler builds a default copy constructor for each class which is doing a memberwise copy between objects.

• Default copy constructors work fine unless the class contains pointer data members ... why???

Page 58: C cpluplus 2

#include <iostream.h>#include <string.h> class mystring { private: char *s; int size; public: mystring(char *); // constructor ~mystring(); // destructor void print(); void copy(char *);}; void mystring::print(){ cout << s << endl;}

Page 59: C cpluplus 2

void string::copy(char *c)

{

strcpy(s, c);

}

 

void main()

{

string str1("George");

string str2 = str1; // default copy constructor

 

str1.print(); // what is printed ?

str2.print();

 

str2.copy("Mary");

 

str1.print(); // what is printed now ?

str2.print();

}

Page 60: C cpluplus 2

Defining a copy constructor

class mystring {

private:

char *s;

int size;

public:

mystring(char *); // constructor

~mystring(); // destructor

string(const mystring&); // copy constructor

void print();

void copy(char *);

};

Page 61: C cpluplus 2

string::string(const string& old_str){ size = old_str.size; s = new char[size+1]; strcpy(s,old_str.s);} 

void main(){ string str1("George"); string str2 = str1; 

str1.print(); // what is printed ? str2.print(); 

str2.copy("Mary"); 

str1.print(); // what is printed now ? str2.print(); } 

-- same results can be obtained by overloading the assignment operator.

Page 62: C cpluplus 2

Inheritance• Objects are often defined in terms of hierarchical

classes with a base class and one or more levels of classes that inherit from the classes that are above it in the hierarchy.

• For instance, graphics objects might be defined as follows:

Page 63: C cpluplus 2

Inheritance

• This hierarchy could, of course, be continued for more levels.

• Each level inherits the attributes of the above level. Shape is the base class. 2-D and 3-D are derived from Shape and Circle, Square, and Triangle are derived from 2-D. Similarly, Sphere, Cube, and Tetrahedron are derived from 3-D.

Page 64: C cpluplus 2

Inheritanceclass A : base class access specifier B

{

member access specifier(s):

...

member data and member function(s);

...

}

Valid access specifiers include public, private, and protected

Page 65: C cpluplus 2

Public Inheritance

public base class (B)

public members

protected members

private members

derived class (A)

public

protected

inherited but not accessible

class A : public B{ // Class A now inherits the members of Class

B// with no change in the “access specifier” for

} // the inherited members

Page 66: C cpluplus 2

Private Inheritance

private base class (B)

public members

protected members

private members

derived class (A)

private

private

inherited but not accessible

class A : private B{ // Class A now inherits the members of Class

B// with public and protected members

} // “promoted” to private

Page 67: C cpluplus 2

Lect 28 P. 67 Winter Quarter

Inheritance (continued)class Shape {

public:int GetColor ( ) ;

protected: // so derived classes can access itint color;

};class Two_D : public Shape{

// put members specific to 2D shapes here};class Three_D : public Shape{

// put members specific to 3D shapes here};

Page 68: C cpluplus 2

Inheritance (continued)class Square : public Two_D{

public:float getArea ( ) ;

protected:float edge_length;

} ;class Cube : public Three_D{

public:float getVolume ( ) ;

protected:float edge_length;

} ;

Page 69: C cpluplus 2

Inheritanceint main ( )

{

Square mySquare;

Cube myCube;

mySquare.getColor ( ); // Square inherits getColor()

mySquare.getArea ( );

myCube.getColor ( ); // Cube inherits getColor()

myCube.getVolume ( );

}

Page 70: C cpluplus 2

Function Overloading

• C++ supports writing more than one function with the same name but different argument lists. This could include:– different data types– different number of arguments

• The advantage is that the same apparent function can be called to perform similar but different tasks. The following will show an example of this.

Page 71: C cpluplus 2

Function Overloadingvoid swap (int *a, int *b) ;

void swap (float *c, float *d) ;

void swap (char *p, char *q) ;

int main ( )

{

int a = 4, b = 6 ;

float c = 16.7, d = -7.89 ;

char p = 'M' , q = 'n' ;

swap (&a, &b) ;

swap (&c, &d) ;

swap (&p, &q) ;

}

Page 72: C cpluplus 2

Function Overloading

void swap (int *a, int *b)

{ int temp; temp = *a; *a = *b; *b = temp; }

void swap (float *c, float *d)

{ float temp; temp = *c; *c = *d; *d = temp; }

void swap (char *p, char *q)

{ char temp; temp = *p; *p = *q; *q = temp; }

Page 73: C cpluplus 2

Operator Overloading • C++ already has a number of types (e.g., int, float, char,

etc.) that each have a number of built in operators. For example, a float can be added to another float and stored in yet another float with use of the + and = operators:

floatC = floatA + floatB;

• In this statement, floatB is passed to floatA by way of the + operator. The + operator from floatA then generates another float that is passed to floatC via the = operator. That new float is then stored in floatC by some method outlined in the = function.

Page 74: C cpluplus 2

Operator Overloading

• Operator overloading means that the operators:

– Have multiple definitions that are distinguished by the types of their parameters, and

– When the operator is used, the C++ compiler uses the types of the operands to determine which definition should be used.

Page 75: C cpluplus 2

Operator Overloading (continued)

• A programmer has the ability to re-define or change how the operators (+, -, *, /, =, <<, >>, etc.) work on their own classes.

• Overloading operators usually consists of defining a class member function called operator+ (where + is any operator). Note that operator is a reserved word in C++. If anything usually follows that operator, it is passed to the function. That function acts exactly like any other member function; it has the same scope as other member functions and can return a value just like any other member function.

Page 76: C cpluplus 2

Operator Overloading

Steps for defining an overloaded operator:

1. Name the operator being overloaded. 2. Specify the (new) types of parameters (operands) the

operator is to receive. 3. Specify the type of value returned by the operator. 4. Specify what action the operator is to perform.

Page 77: C cpluplus 2

Friendship

• A friend function of a class is defined outside the class’s scope (I.e. not member functions), yet has the right to access the non-public members of the class.

• Single functions or entire classes may be declared as friends of a class.

• These are commonly used in operator overloading. Perhaps the most common use of friend functions is overloading << and >> for I/O.

Page 78: C cpluplus 2

Friends

• Basically, when you declare something as a friend, you give it access to your private data members.

• This is useful for a lot of things – for very interrelated classes, it more efficient (faster) than using tons of get/set member function calls, and they increase encapsulation by allowing more freedom is design options.

Page 79: C cpluplus 2

Friends

• A class doesn't control the scope of friend functions so friend function declarations are usually written at the beginning of a .h file. Public and private don't apply to them.

Page 80: C cpluplus 2

Friends

• Friendship is not inherited, transitive, or reciprocal.– Derived classes don’t receive the privileges of friendship (more on

this when we get to inheritance in a few classes)

– The privileges of friendship aren’t transitive. If class A declares class B as a friend, and class B declares class C as a friend, class C doesn’t necessarily have any special access rights to class A.

– If class A declares class B as a friend (so class B can see class A’s private members), class A is not automatically a friend of class B (so class A cannot necessarily see the private data members of class B).

Page 81: C cpluplus 2

FriendsExample

Page 82: C cpluplus 2

82

Polymorphism Compile-Time Binding vs.

Run-Time Binding

• A function’s name is associated with an entry point, the starting address of the code that implements the function

• Compile-time binding lets the compiler determines what code is to be executed when a function name is invoked

• Run-time binding is the binding of a function’s name to an entry point when the program is running

Page 83: C cpluplus 2

83

Compile-Time Binding#include <iostream>

using namespace std;

void sayHi();

int main() {

sayHi();

return 0;

}

void sayHi() {

cout <<"Hello, cruel world!"<< endl;

}

Page 84: C cpluplus 2

84

Requirements for C++ Polymorphism

• There must be an inheritance hierarchy

• The classes in the hierarchy must have a virtual method with the same signature

• There must be either a pointer or a reference to a base class. The pointer or reference is used to invoke a virtual method

Page 85: C cpluplus 2

85

PolymorphismExample