Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to C++ Programming

Similar presentations


Presentation on theme: "Introduction to C++ Programming"— Presentation transcript:

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

2 Agenda Session 1 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 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

3 C++ : Historical Perspective
What is C++ ? Who invented C++ ? Who are the users of C++ ?

4 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

5 Basics of C++ Structure of a C++ program Variables and Data types
Constants Operators Basic Input / output

6 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; }

7 Structure of a C++ Program
Comment /* greeting.cpp greets its user. * * Input: The name of the user * Output: A personalized greeting *********************************************************/ #include <iostream> // cin, cout, <<, >> #include <string> // string using namespace std; int main() { cout << "Please enter your first name: "; string firstName; cin >> firstName; cout << "\nWelcome to the world of C++, " << firstName << "!\n"; } Compiler directives Specifies standard related names Main portion of program. Contains C++ statements.

8 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

9 Fundamental DataTypes

10 More on Variables Declaration – Initialization – Assignment-
int number1; float number2; Initialization – int number1 = 0; int number2 = 3.3; Assignment- number1=5; number2=number1;

11 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.

12 Scope of Variables

13 Initialization of Variables
Two possibilities: type identifier = initial_value ; type identifier (initial_value) ;

14 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; }

15 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");

16 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"; return 0; } .

17 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.

18 Declared Constants (const)
Use the “const” prefix you can declare constant with specific type Examples: const int radius = 100; const char tabulator = '\t';

19 Arithmetic Operators Assignment 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; }

20 Arithmetic Operators Compound assignment
Increment & Decrement ( ++,--) Relational and equality operators ( ==, !=, >, <, >=, <= )

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

22 Arithmetic Operators + addition - subraction * multiplication
/ division % modulo or remainder

23 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;

24 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

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

26 Control structures Example

27 Control structures Example

28 Switch Statement switch (x) { \ case 1: cout << "x is 1"; break;
default: cout << "value of x unknown"; }

29 Functions We can use functions to achieve structured programming
Int 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

30 Functions Example

31 Passing Parameters Call By Value Call By Reference
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

32 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

33 Arrays An Array is a set of elements of the same type located in contiguous memory locations. An Array can be referenced using index

34 Arrays Intialization Accessing Passing arrays as parameters
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);

35 Arrays Example

36 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

37 Address Operator (&) The ‘&’ operator returns the ‘address of’ its operand. ‘&’ can be translated ‘address of’

38 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”

39 Pointers Example

40 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

41 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

42 Dynamic Memory Example

43 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

44 Accessing the struct members
We use the ‘.’ to access members of a struct cout << person1.fname; person1.fname=“John”;

45 Structs Example

46 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);

47 Agenda Session 1 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 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

48 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

49 C++ Classes Example

50 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. .

51 Constructors Example 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;

52 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

53 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 In case the program ends , or the function ends ( scope ), or a delete is called

54 Destructors Example 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;

55 Copy Constructor A member function which initializes an object using another object of the same class. Copy constructor prototype myclass (const myname&);

56 Copy Constructor Example
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 };

57 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???

58 #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; }

59 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 ?

60 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 *); };

61 string::string(const string& old_str) size = old_str.size;
{ 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 ? -- same results can be obtained by overloading the assignment operator.

62 Engineering H192 Winter 2005 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: Instructor notes: Here we begin a brief introduction to inheritance in C++. Inheritance makes it possible to establish a hierarchy of classes where classes that are lower in the hierarchy automatically take on the characteristics of the classes above. So, as we’d expect, the most general class in the hierarchy is at the top and as you proceed downward, the classes become more specialized. This slide indicates this by starting with a very general shape class and progressing downward to more specialized, first with the number of dimensions and then to even more specialized shapes within one of the two dimensional classes. Lecture 28

63 Engineering H192 Winter 2005 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. Lecture 28

64 Inheritance class A : base class access specifier B {
Engineering H192 Winter 2005 Inheritance class A : base class access specifier B { member access specifier(s): ... member data and member function(s); } Valid access specifiers include public, private, and protected Lecture 28

65 Public Inheritance class A : public B
Engineering H192 Winter 2005 Public Inheritance class A : public B { // Class A now inherits the members of Class B // with no change in the “access specifier” for } // the inherited members public base class (B) public members protected members private members derived class (A) public protected inherited but not accessible Lecture 28

66 Private Inheritance class A : private B
Engineering H192 Winter 2005 Private Inheritance class A : private B { // Class A now inherits the members of Class B // with public and protected members } // “promoted” to private private base class (B) public members protected members private members derived class (A) private inherited but not accessible Lecture 28

67 Inheritance (continued)
Engineering H192 Winter 2005 Inheritance (continued) class Shape { public: int GetColor ( ) ; protected: // so derived classes can access it int 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 Winter Quarter Lecture 28

68 Inheritance (continued)
Engineering H192 Winter 2005 Inheritance (continued) class Square : public Two_D { public: float getArea ( ) ; protected: float edge_length; } ; class Cube : public Three_D float getVolume ( ) ; Lecture 28

69 Inheritance int main ( ) { Square mySquare; Cube myCube;
Engineering H192 Winter 2005 Inheritance int main ( ) { Square mySquare; Cube myCube; mySquare.getColor ( ); // Square inherits getColor() mySquare.getArea ( ); myCube.getColor ( ); // Cube inherits getColor() myCube.getVolume ( ); } Lecture 28

70 Engineering H192 Winter 2005 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. Lecture 28

71 Function Overloading void swap (int *a, int *b) ;
Engineering H192 Winter 2005 Function Overloading void 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 = ; char p = 'M' , q = 'n' ; swap (&a, &b) ; swap (&c, &d) ; swap (&p, &q) ; } Lecture 28

72 Function Overloading void swap (int *a, int *b)
Engineering H192 Winter 2005 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; } Lecture 28

73 Engineering H192 Winter 2005 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. Lecture 28

74 Operator Overloading Operator overloading means that the operators:
Engineering H192 Winter 2005 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. Lecture 28

75 Operator Overloading (continued)
Engineering H192 Winter 2005 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. Lecture 28

76 Steps for defining an overloaded operator:
Engineering H192 Winter 2005 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. Instructor notes: Lecture 28

77 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.

78 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.

79 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.

80 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).

81 Friends Example

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

83 Compile-Time Binding #include <iostream> using namespace std;
void sayHi(); int main() { sayHi(); return 0; } void sayHi() { cout <<"Hello, cruel world!"<< endl;

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

85 Polymorphism Example


Download ppt "Introduction to C++ Programming"

Similar presentations


Ads by Google