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
C++ : Historical Perspective
• What is C++ ?
• Who invented C++ ?
• Who are the users of C++ ?
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
Basics of C++
• Structure of a C++ program
• Variables and Data types
• Constants
• Operators
• Basic Input / output
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
/* 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.
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
Fundamental DataTypes
More on Variables
• Declaration – – int number1;– float number2;
• Initialization –– int number1 = 0;– int number2 = 3.3;
• Assignment-– number1=5;– number2=number1;
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.
Scope of Variables
Initialization of Variables
Two possibilities:
• type identifier = initial_value ;
• type identifier (initial_value) ;
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;
}
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");
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;
}
.
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.
Declared Constants (const)
• Use the “const” prefix you can declare constant with specific type
Examples:
– const int radius = 100;
– const char tabulator = '\t';
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;
}
Arithmetic Operators Compound assignment
Increment & Decrement ( ++,--)
Relational and equality operators ( ==, !=, >, <, >=, <= )
Arithmetic Operators Logical Operators ( !, &&, || )
Arithmetic Operators
• + addition
• - subraction
• * multiplication
• / division
• % modulo or remainder
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;
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
Control structures
• if (cond) state1 else if (cond2) state2 else state3• while (expression) statement• do statement while (cond)• for (init; cond; increment) statement;
Control structuresExample
Control structuresExample
Switch Statement
switch (x) { \
case 1:
cout << "x is 1";
break;
case 2:
cout << "x is 2";
break;
default:
cout << "value of x unknown";
}
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
FunctionsExample
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
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
Arrays
• An Array is a set of elements of the same type located in contiguous memory locations.
• An Array can be referenced using index
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);
ArraysExample
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
Address Operator (&)
• The ‘&’ operator returns the ‘address of’ its operand.
• ‘&’ can be translated ‘address of’
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”
PointersExample
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
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
Dynamic MemoryExample
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
Accessing the struct members
• We use the ‘.’ to access members of a structcout << person1.fname;
person1.fname=“John”;
StructsExample
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);
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
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
C++ ClassesExample
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.
.
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;
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
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
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;}
Copy Constructor
• A member function which initializes an object using another object of the same class.
• Copy constructor prototype
myclass (const myname&);
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
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???
#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;}
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();
}
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 *);
};
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.
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:
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.
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
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
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
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};
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;
} ;
Inheritanceint main ( )
{
Square mySquare;
Cube myCube;
mySquare.getColor ( ); // Square inherits getColor()
mySquare.getArea ( );
myCube.getColor ( ); // Cube inherits getColor()
myCube.getVolume ( );
}
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.
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) ;
}
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; }
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.
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.
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.
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.
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.
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.
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.
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).
FriendsExample
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
PolymorphismExample