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

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

Embed Size (px)

Citation preview

Page 1: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

Introduction to C++ Programming

Csci 169

Prof.A.Bellaachia

And

Anasse Bari

Page 2: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

C++ : Historical Perspective

• What is C++ ?

• Who invented C++ ?

• Who are the users of C++ ?

Page 4: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

Basics of C++

• Structure of a C++ program

• Variables and Data types

• Constants

• Operators

• Basic Input / output

Page 6: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

Fundamental DataTypes

Page 10: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

More on Variables

• Declaration – – int number1;– float number2;

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

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

Page 11: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

Scope of Variables

Page 13: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

Initialization of Variables

Two possibilities:

• type identifier = initial_value ;

• type identifier (initial_value) ;

Page 14: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

Arithmetic Operators Compound assignment

Increment & Decrement ( ++,--)

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

Page 21: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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

Page 22: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

Arithmetic Operators

• + addition

• - subraction

• * multiplication

• / division

• % modulo or remainder

Page 23: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

Control structuresExample

Page 27: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

Control structuresExample

Page 28: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

FunctionsExample

Page 31: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

ArraysExample

Page 36: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

Address Operator (&)

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

• ‘&’ can be translated ‘address of’

Page 38: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

PointersExample

Page 40: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

Dynamic MemoryExample

Page 43: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

Accessing the struct members

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

person1.fname=“John”;

Page 45: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

StructsExample

Page 46: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

C++ ClassesExample

Page 50: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

Copy Constructor

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

• Copy constructor prototype

myclass (const myname&);

Page 56: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

#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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

Inheritanceint main ( )

{

Square mySquare;

Cube myCube;

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

mySquare.getArea ( );

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

myCube.getVolume ( );

}

Page 70: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

FriendsExample

Page 82: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

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: Introduction to C++ Programming Csci 169 Prof.A.Bellaachia And Anasse Bari

85

PolymorphismExample