c96e1 session3 c++

80
1 Subject Name - C++ Semester - II Neetu Gupta

Upload: mukund-trivedi

Post on 02-Nov-2014

643 views

Category:

Technology


2 download

DESCRIPTION

 

TRANSCRIPT

Page 1: C96e1 session3 c++

1

Subject Name - C++

Semester - II

Neetu Gupta

Page 2: C96e1 session3 c++

Contents

• Arrays• Multidimensional Arrays• Pointers• Classes – A simple class• Inline member function• Constructor• Destructor• Member initialization list• Const members

Page 3: C96e1 session3 c++

Contents

• static members

• member pointers

• Class object

• Object arrays

Page 4: C96e1 session3 c++

Arrays• An array is a series of elements of the same type placed in contiguous memory

locations that can be individually referenced by adding an index to a unique identifier.

• That means that, for example, we can store 5 values of type int in an array without having to declare 5 different variables, each one with a different identifier. Instead of that, using an array we can store 5 different values of the same type, int for example, with a unique identifier.

For example, an array to contain 5 integer values of type int called billy could be represented like this:

• where each blank panel represents an element of the array, that in this case are integer values of type int. These elements are numbered from 0 to 4 since in arrays the first index is always 0, independently of its length.

Page 5: C96e1 session3 c++

Array - Declaration

• Like a regular variable, an array must be declared before it is used. A typical declaration for an array in C++ is:

type name [elements];

where type is a valid type (like int, float...), name is a valid identifier and the elements field (which is always enclosed in square brackets []), specifies how many of these elements the array has to contain.

Page 6: C96e1 session3 c++

• Therefore, in order to declare an array called billy as the one shown in the above diagram it is as simple as:

 int billy [5];

• The elements field within brackets [] which represents the number of elements the array is going to hold, must be a constant value, since arrays are blocks of non-dynamic memory whose size must be determined before execution. In order to create arrays with a variable length dynamic memory is needed, which is explained later in these tutorials.

Page 7: C96e1 session3 c++

Initializing arrays.

• When declaring a regular array of local scope (within a function, for example), if we do not specify otherwise, its elements will not be initialized to any value by default,

• In both cases, local and global, when we declare an array, we have the possibility to assign initial values to each one of its elements by enclosing the values in braces { }.

Page 8: C96e1 session3 c++

• For example:

  int billy [5] = { 16, 2, 77, 40, 12071 };

This declaration would have created an array like this:

• When an initialization of values is provided for an array, C++ allows the possibility of leaving the square brackets empty [ ]. In this case, the compiler will assume a size for the array that matches the number of values included between braces { }:

 int billy [] = { 16, 2, 77, 40, 12071 };

After this declaration, array billy would be 5 ints long, since we have provided 5 initialization values.

Page 9: C96e1 session3 c++

Accessing Array Values• we can access the value of any of its elements individually as if it

was a normal variable, thus being able to both read and modify its value. The format is as simple as:

array-name [index]

• For example, to store the value 75 in the third element of billy, we could write the following statement:

  billy[2] = 75;

• For example, to store the value 75 in the third element of billy, we could write the following statement:

  billy[2] = 75;

Page 10: C96e1 session3 c++

• // arrays example #include <iostream> using namespace std; int x [] = {2,3,4,5,6}; int n, result=0; int main () {

for ( n=0 ; n<5 ; n++ ) { result += x [n];

} cout << “Sum of array elements is: “ << result; return 0;

}

Output is: Sum of array elements is: 20

Page 11: C96e1 session3 c++

Multidimensional Arrays

• Multidimensional arrays can be described as "arrays of arrays".

• For example, a bidimensional array can be imagined as a bidimensional table made of elements, all of them of a same uniform data type.

• Here, jimmy represents a bidimensional array of 3 per 5 elements of type int.

Page 12: C96e1 session3 c++

Multidimensional Arrays

• The way to declare this array in C++ would be:

 int jimmy [3][5];

• the way to reference the second element vertically and fourth horizontally in an expression would be:  jimmy[1][3]

Page 13: C96e1 session3 c++

Pointers

• Pointers are variables those store the address of any other variable.

• The value saved into a pointer type variable is interpreted as memory address.

• We can say that pointer is like any other variable but the value it stores is the address of some other variable

Page 14: C96e1 session3 c++

Pointer declaration

• We can delare a pointer as

type *<name of pointer type variable>

• Example

int *iptr; // poniter to int type variable

char *iptr; // poniter to char type variable

double *iptr; // poniter to double type variable

Page 15: C96e1 session3 c++

Address Operator – Pointer initialization

• We can initialize a pointer variable with address of a variable with the help of & operator

• Be careful about the data types. We can initialize a pointer to int type with the address of an int type variable only. The same applies to all other data types

Page 16: C96e1 session3 c++

• Once we change the value of i, the address in iptr will remain unchanged but the value pointed by iptr will also become same as i.

int i, *iptr

Iptr = &i; Address of x i.e. 4000

i = 40 40 Address of x i.e. 4000

I at 4000 iptr

Page 17: C96e1 session3 c++

• Usually, pointer variables hold address to a specific kinds of data (e.g.: address of an int, address of a char, etc)

int * p; /* variablep can hold the address of a memory location

that contains an int */ char * chptr; /* chptr can hold the address of a memory

location that contains achar */

p and chptr both are pointers and can store addresses but p can only store address of a variable which is int and chptr can store address of a variable which is of char type.

Page 18: C96e1 session3 c++

Dereferencing Operator

• We can use the value of variable that a pointer points to with the help of * operator. Here,* is called the dereferencing operator

• The expression *p denotes the value of memory cell to which p points

• Be careful not to dereference a pointer that has not yet been initialized.

Page 19: C96e1 session3 c++

int i =10;

int * iptr = &10; // Initialize a pointer with an address

i = 10 iptr = 2000

2000

Here i is an int variable store at location 2000 in memory

*p will be 10

p will be 2000 i.e. the address value at which I is stored in memory

Page 20: C96e1 session3 c++

Pointer arithmetic

• To conduct arithmetical operations on pointers is a little different than to conduct them on regular integer data types.

• Only addition and subtraction operations are allowed to be conducted with them

• Assume that in a given compiler for a specific machine, char takes 1 byte, short takes 2 bytes and long takes 4

Page 21: C96e1 session3 c++

• Suppose that we define three pointers in this compiler and they point to memory location 1000, 2000, 3000 respectively:

char *mychar; short *myshort; long *mylong;

• If we write the code as:mychar++; myshort++; mylong++;

Page 22: C96e1 session3 c++

• When mychar is incremented it is incremented by value 1 i.e. size of char

• When myshort is incremented it is incremented by value 2 i.e. size of short type

• When mylong is incremented it is incremented by value 4 i.e. size of long type

Page 23: C96e1 session3 c++

• The same is applied to ++ or – operator.• A pointer is incremented or decremented

as much as the size of type it holds

short s1 ,short *sptr = &sptr;sptr = sptr+2.

Here if spr is 1000 initially it will be 1004 after adding two. As the size of one short is 2. Ans we are adding 2 that means 2*size of short type i.e. 4 now.

Page 24: C96e1 session3 c++

Classes

• A user defined data type

• It can hold both

the data and

the functions that operates on data.

• The elements in class – data & functions are called members of the class

Page 25: C96e1 session3 c++

class syntax

• Classes in C++ can be declared using the keyword class, with format:

class class_name { access_specifier_1:

member1;

access_specifier_2:

member2; ...

};

Here class_name is a valid identifier for the class,

Page 26: C96e1 session3 c++

• The body of the declaration can contain members, that can be either data or function declarations, and optionally access specifiers.

• We can also declare a variable of class type, such a variable is called object of that class

class-type object-name;

Page 27: C96e1 session3 c++

// Class Rectangle - classes example #include <iostream> using namespace std; class Rectangle {

public: int x, y;void set_values (int , int); int area () {

return (x*y);}

};

void Rectangle::set_values (int a, int b) { x = a; y = b;

}

Page 28: C96e1 session3 c++

• Declares a class (i.e., a user-defined type) called Rectangle.

• This class contains four members: – two data members of type int (member x and member

y) with private access (because private is the default access level) and

– two member functions with public access: set_values() and area()

– The most important new thing in this code is the operator of scope (::, two colons) included in the definition of set_values(). It is used to define a member of a class from outside the class definition itself.

Page 29: C96e1 session3 c++

• We can declare a variable of type Rectangle as

Rectangle rect1, rect2

Here, rect1 and rect2 are two objects of type Rectangle.

Page 30: C96e1 session3 c++

• After the previous declarations of Rectangle and rect1, we can refer within the body of the program to any of the public members of the object rect1 as if they were normal functions or normal variables, just by putting the object's name followed by a dot (.) and then the name of the member.

rect1.set_values (3,4);

myarea = rect1.area();

Access member variable (.)

Page 31: C96e1 session3 c++

// Rectangle – Class Example #include <iostream> using namespace std; class Rectangle {

int x, y; public:

void set_values (int,int); int area () {return (x*y);}

};

void Rectangle::set_values (int a, int b) { x = a; y = b;

}

int main () { Rectangle rect; // Object of type Rectanglerect.set_values (3,4); cout << "area: " << rect.area(); return 0;

}

Page 32: C96e1 session3 c++

Explanation of the previous programme

• The most important new thing in this code is the operator of scope (::, two colons) included in the definition of set_values(). It is used to define a member of a class from outside the class definition itself.

• You may notice that the definition of the member function area() has been included directly within the definition of the Rectangleclass given its extreme simplicity, whereas set_values() has only its prototype declared within the class, but its definition is outside it. In this outside declaration, we must use the operator of scope (::) to specify that we are defining a function that is a member of the class Rectangleand not a regular global function.

• The only difference between defining a class member function completely within its class or to include only the prototype and later its definition, is that in the first case the function will automatically be considered an inline member function by the compiler, while in the second it will be a normal (not-inline) class member function, which in fact supposes no difference in behavior.

Page 33: C96e1 session3 c++

Access specifiers• Access specifier of a class member decides

where that member can be used or not used.• These specifiers modify the access rights that

the members following them acquire:

private protected public

• If we do not specify any access specifier while declaring it, then default access specifier is private.

Page 34: C96e1 session3 c++

1. private members of a class are accessible only from within other members of the same class or from their friends.

2. protected members are accessible from members of their same class and from their friends, but also from members of their derived classes.

3. public members are accessible from anywhere where the object is visible.

Page 35: C96e1 session3 c++

class Rectangle { int x, y; public:

void set_values (int,int); int area (void);

}• Here, no specifier is associated with

members x and y, so these are private• Both the member functions are declared

as public

Page 36: C96e1 session3 c++

• If we have a program as below:int main () {

Rectangle rect; // Object of typerect.x = 3; // Errorrect.y = 4 // Errorrect.set_values (3,4); cout << "area: " << rect.area(); return 0;

}

We can not access x, y in main function as these are declared as private in class Rectangle.

Page 37: C96e1 session3 c++

Constructor

• Objects generally need to initialize variables or assign dynamic memory during their process of creation

• Like in class we used a function set_values() to set the values of class variables x and y.

• what would happen if in the previous example we called the member function area() before having called function set_values()?

• We can avoid such situations with the use of special function called constructor.

Page 38: C96e1 session3 c++

Constructor

• A member function in a class which is automatically called whenever a new object of this class is created.

• Rules are :1. This constructor function must have the

same name as the class, 2. and cannot have any return type; not even

void.

Page 39: C96e1 session3 c++

// Rectangle – Class Example #include <iostream> using namespace std; class Rectangle {

int x, y; public:

Rectangle (int , int); // constructor declarationint area () {return (x*y);}

};

// Definition of constructor Rectangle::Rectangle (int a, int b) {

width = a; height = b;

}

Page 40: C96e1 session3 c++

In the example, class Rectangle has a member function with name Rectangle

• This is the constructor of class Rectangle.

• Note that the function has no return type – not even void

Page 41: C96e1 session3 c++

Constructors call

• A constructor gets automatically called when the object of class is created.

Rectangle rect(10,20)

Here, the constructor provided in class will get called and the values 10,20 will get passed to variables x and y.

Page 42: C96e1 session3 c++

int main () { Rectanglerect1 (3,4); Rectangle rect2 (5,6); cout << "rect1 area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0;

} Here, two objects of type Rectangle is created with

the use of constructor. • For rect1 constructor is called with parameter

values are 3,4.• For rect2 constructor is called with parameter

values are 5,6.

Page 43: C96e1 session3 c++

Default Constructor

• If you do not declare any constructors in a class definition, the compiler adds to the class a default constructor with no arguments.

• Therefore, if you declare a class like this:class Rectangle {

int x, y; public:

int area () {return (x*y);

} };

The compiler assumes that Rectangle has a default constructor with no arguments

Page 44: C96e1 session3 c++

• You can declare objects of this class by simply declaring them without any arguments:

Rectangle rect1;

• Here, the compiler calls the default constructor with no arguments even though we have not added any constructor into the class Rectangle.

Page 45: C96e1 session3 c++

Remember

• If you declare your own constructor for a class, the compiler no longer provides a default constructor.

• In that case, we you need to have a constructor with no arguments, then you have to write that explicitly into the class.

Page 46: C96e1 session3 c++

• If the Rectangle class has a constructor asclass Rectangle {

int x, y; public:

Rectangle (int , int); // constructor declarationint area () {

return (x*y);}

};

HereThis code will work

Rectangle rect(10,10); // CorrectBut

Rectangle rect; // Errorwill not work

Page 47: C96e1 session3 c++

Destructor

• The destructor are opposite to constrcutors in functinality

• It is automatically called when an object is destroyed. An object is destroyed when– its scope of existence has finished– it is an object dynamically assigned and it is

released using the operator delete

Page 48: C96e1 session3 c++

• The second code does not work because, the constructor that we defined has overrided the default constructor provided by compiler.

• If we need the default one also, we should provide that as well in the class as

class Rectangle { int x, y; public:

Rectangle (int , int); // constructor declaration

Rectangle (); // Default constructor declaration

int area () {return (x*y);

} };

Page 49: C96e1 session3 c++

Destructor

• The destructor must have the same name as the class, but preceded with a tilde sign (~)

• A destructor must also return no value i.e. no return type

• A destructor must also have no parameters.

Page 50: C96e1 session3 c++

// example on constructors and destructors#include <iostream> using namespace std; class Rectangle{

int *width, *height; public:

Rectangle (int, int); ~Rectangle(); // Destructor declarartionint area () {

return (*width * *height);}

};

Rectangle :: Rectangle (int a, int b) { width = new int; height = new int; *width = a; *height = b;

}

Rectangle ::~Rectangle() { // Destructor definitioncout << “ In destructor of Rectangle class \n”;delete width; delete height;

}

Page 51: C96e1 session3 c++

• In the above example we declare a member function with name ~Rectangle();

• This is the destructor for the class Rectangle, which has no parameters and no return type

Page 52: C96e1 session3 c++

• We can use a destructor as below in a main() fucntionint main () {

Rectangle rect (3,4);cout << "rect area: " << rectb.area();return 0;

} Output is

rect area: 12In destructor of class Rectangle.

• rect object is created and initialized with values 3,4.• The destructor of this object is called when rect goes out

of scope

Page 53: C96e1 session3 c++

Pointers to classes

• It is valid to create pointers that point to classes

• A class becomes a valid type, so we can use the class name as the type for the pointer

• For example we can have a pointer to an object of type Rectangle as

Rectangle *rect;

Page 54: C96e1 session3 c++

• To use directly a member of an object pointed by a pointer we can use the arrow operator (->) of indirection.

• To use the members of class Rectangle using pointer

Rectangle * rect;

rect = new Rectangle (10,20);

// calls the area() function on the object pointed by

// pointer rect

rect->area();

Page 55: C96e1 session3 c++

• We can create a new object and assign it to a pointer as

Rectangle * rect = new Recatngle(10,20);

• We can assign the address of already created object to a newly declared pointer. For this we make use of the “address of” operator (&) as

Rectangle rectObj(10,20);

Rectangle rectPtr = &rectObj.

Page 56: C96e1 session3 c++

• // pointer to classes example #include <iostream> using namespace std; class Rectangle {

int width, height; public:

void set_values (int, int); int area (void) {

return (width * height);}

};

void Rectangle::set_values (int a, int b) { width = a; height = b;

}

Page 57: C96e1 session3 c++

int main () { Rectangle a, *b, *c; b= new Rectangle; c= &a; a.set_values (1,2); b->set_values (3,4); cout << "a area: " << a.area() << endl; cout << "*b area: " << b->area() << endl; cout << "*c area: " << c->area() << endl; delete b; return 0;

}

Output is

a area: 2 *b area: 12 *c area: 2

Page 58: C96e1 session3 c++

Object Arrays

• The way we declare an array of simple data types, we can also declare an array of class type

• Here each element is an object of that class type and we can refer to it using [] operator.

Page 59: C96e1 session3 c++

// Array of objects

int main () {

Rectangle objR[5];

// first element can be referd as objR[0]

cout << “Area of first object is: “ << objR[0].area();

cout << “Area of second object is: “ << objR[1].area();

………..

}

Here objR is an array of objects of type Rectangle. Each object can be used with name bjR followed by [], provided with an index value.

Page 60: C96e1 session3 c++

Summary

Expression Meaning*x pointed by x

&x Address of x

x.y Member y of object x

x->y Member y of object pointed by x

Page 61: C96e1 session3 c++

Static member

• When a member of class is declared as static it has a special different meaning

• A class can contain static members, either data or functions.

• There is only one copy of static member of a class which is being shared by all the objects of the class

• That is why we can also call the static members of a class as “class variable”.

Page 62: C96e1 session3 c++

• If you declare a variable without static, that means it is an instance variable.

• This means that every object will have its own copy of that variable.

• In example below any object of type Dummy will have its own copy

class Dummy {int x, y;public: Dummy (int I, int j) {

x = i;y = j;

}}

Page 63: C96e1 session3 c++

• Here the variable count is declared static, it will be shared by all object like If we declare two object as

int main () { Dummy a(10,20), b(100,200); return 0;

}• In this case objects will be as below. Objects a and b has

its own copy of static member

Object a

Y = 20

X = 10

Object b

Y = 200

X = 100

Page 64: C96e1 session3 c++

• If we add a static member to class Dummy

class Dummy {int x, y;static int count;public: Dummy (int I, int j) {

x = i;y = j;count++;

}}int Dummy::count = 0;

• we can only include the prototype (its declaration) in the class declaration but not its definition (its initialization). We should initialize a static data-member with a formal definition outside the class as

int Dummy::count = 0;

Page 65: C96e1 session3 c++

• Here both the objects will point to a single copy of count variable.

Object a

Y = 20

X = 10

Object b

Y = 200

X = 100

count

Page 66: C96e1 session3 c++

class Dummy {int x, y;static int count;public: Dummy (int I, int j) {

x = i;y = j;count++;

}}int Dummy::count = 0;

int main () {

Dummy a(10,20), b(100,200);

cout << “count in a ;” << a.count;

cout << “count in b ;” << b.count;

return 0;

}

Output iscount in a : 2count in b : 2

Both the objects have same value

Page 67: C96e1 session3 c++

Static function

• Similarly we can declare a function as static.

• We should then call this function using operator :: with class name as

class_name::static_member

Page 68: C96e1 session3 c++

// class with static member functionclass Dummy {

int x, y;static int count;public: Dummy (int I, int j) {

x = i;y = j;count++;

}static int getCount() {

}

}int Dummy::count = 0;

Page 69: C96e1 session3 c++

int main () {

Dummy a(10,20), b(100,200);

cout << “count in a ;” << Dummy::getCount();

cout << “count in b ;” << Dummy::getCount();;

return 0;

}

• Here notice the code Dummy::getCount(); getCount() is a static function and it is called using the class name with operator ::

Page 70: C96e1 session3 c++

Constant Members function• We can declare a function as const

member function.

• A function declared as const can not alter any data member in the class

• A member function is declared as constant with the use of keyword const, prefixed with function prototype as

const return_type function_name (parameters);

Page 71: C96e1 session3 c++

class Dummy {int x, y;public: Dummy (int I, int j) {

x = i;y = j;

}const int getX() {

return x;}const int getY() {

return y;}

}

• Here, the functions getX() and getY() should not modify any data, hence we declared them as constant.

Page 72: C96e1 session3 c++

• If we change the code of getX() or getY() as

const int getX() {x= 10; // Compilation Error

return x;}

• So declaring as function const is a message to compiler that this function should not modify any data in the class.

Page 73: C96e1 session3 c++

const member variable

• We can also declare a variable as const in a class

const int id;

• That means once initialized with a value the content of variable id can not be changed.

Page 74: C96e1 session3 c++

Initializing const variable

• The only place to initialize a const variable is to initialize in the initialization list.

• As discussed before, initializing the value in the initialization list is not as same as assigning a value..

• If a class has two variables id (const) and age (non-const), then the initialization for these will be as

int id, age;public: Employee (int I, int j) : id (i) { // Initialize

age = j; // Assignment}

Page 75: C96e1 session3 c++

// class const variable member - Exampleclass Employee {

const int id;int age;public:

Employee (int I, int j) : id (i) { // Initializeage = j; // Assignment

}void set_values (int i, int j) {

id = i; // Compilation Errorage = j;

}}

Here we can initialize the id in initialization list but can not assign it any value later in any other function as set_value() here.

Page 76: C96e1 session3 c++

Initialization list

• C++ provides a way of initializing member variables when they are created rather than afterwards using initialization list.

• The initialization list is inserted after the constructor parameters, begins with a colon (:), and then lists each variable to initialize along with the value for that variable separated by a comma.

Page 77: C96e1 session3 c++

• Take an example as below which do not use initialization list. It does explicit assignments in the constructor body

class Rectangle { int width, height; public:

Rectangle (int w, int h) {width = w;height = h;

}};

• This assignment not initialization

Page 78: C96e1 session3 c++

• Now see the code using initialization list

class Rectangle {

int width, height;

public:

Rectangle (int w, int h) : width (w), height (h) {

}

};

Here width and height are initialized using initialization list not using assighment.

Page 79: C96e1 session3 c++

Note that

• we no longer need to do the explicit assignments in the constructor body, since the initializer list replaces that functionality.

• the initialization list does not end in a semicolon.

Page 80: C96e1 session3 c++

Thank You

80