2. Contents
• Arrays
• Multidimensional Arrays
• Pointers
• Classes – A simple class
• Inline member function
• Constructor
• Destructor
• Member initialization list
• Const members
3. Contents
• static members
• member pointers
• Class object
• Object arrays
4. 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.
5. 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.
6. • 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.
7. 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 { }.
8. • 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.
9. 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;
10. • // 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
11. 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.
12. 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]
13. 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
14. 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
15. 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
16. I at 4000 iptr
int i, *iptr
Iptr = &i; Address of x
i.e. 4000
i = 40 40 Address of x
i.e. 4000
• 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.
17. • 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.
18. 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.
19. int i =10;
int * iptr = &10; // Initialize a pointer with an
address
*p will be 10
p will be 2000 i.e.
i = 10 iptr = 2000 the address value
at which I is
2000 stored in memory
Here i is an int variable store at location
2000 in memory
20. 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
21. • 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++;
22. • 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
23. • 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.
24. 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
25. 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,
26. • 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;
27. // 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;
}
28. • 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.
29. • We can declare a variable of type
Rectangle as
Rectangle rect1, rect2
Here, rect1 and rect2 are two objects of type
Rectangle.
30. Access member variable (.)
• 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();
31. // 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 Rectangle
rect.set_values (3,4);
cout << "area: " << rect.area();
return 0;
}
32. 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.
33. 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.
34. • private members of a class are
accessible only from within other
members of the same class or from their
friends.
• protected members are accessible from
members of their same class and from
their friends, but also from members of
their derived classes.
• public members are accessible from
anywhere where the object is visible.
35. 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
36. • If we have a program as below:
int main () {
Rectangle rect; // Object of type
rect.x = 3; // Error
rect.y = 4 // Error
rect.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.
37. 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.
38. 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.
39. // Rectangle – Class Example
#include <iostream>
using namespace std;
class Rectangle {
int x, y;
public:
Rectangle (int , int); // constructor declaration
int area () {return (x*y);}
};
// Definition of constructor
Rectangle::Rectangle (int a, int b) {
width = a;
height = b;
}
40. 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
41. 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.
42. 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.
43. 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
44. • 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.
45. 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.
46. • If the Rectangle class has a constructor as
class Rectangle {
int x, y;
public:
Rectangle (int , int); // constructor declaration
int area () {
return (x*y);
}
};
Here
This code will work
Rectangle rect(10,10); // Correct
But
Rectangle rect; // Error
will not work
47. 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
48. • 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);
}
};
49. 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.
50. // example on constructors and destructors
#include <iostream>
using namespace std;
class Rectangle{
int *width, *height;
public:
Rectangle (int, int);
~Rectangle(); // Destructor declarartion
int area () {
return (*width * *height);
}
};
Rectangle :: Rectangle (int a, int b) {
width = new int;
height = new int;
*width = a;
*height = b;
}
Rectangle ::~Rectangle() { // Destructor definition
cout << “ In destructor of Rectangle class n”;
delete width;
delete height;
}
51. • 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
52. • We can use a destructor as below in a main() fucntion
int main () {
Rectangle rect (3,4);
cout << "rect area: " << rectb.area();
return 0;
}
Output is
rect area: 12
In 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
53. 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;
54. • 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();
55. • 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.
56. • // 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;
}
57. 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
58. 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.
59. // 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.
60. 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
61. 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”.
62. • 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;
}
}
63. • 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
X = 10 X = 100
Y = 20 Y = 200
Object a Object b
64. • 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;
65. X = 10 X = 100
Y = 20 Y = 200
Object a Object b
count
• Here both the objects will point to a single
copy of count variable.
66. class Dummy { int main () {
int x, y;
Dummy a(10,20), b(100,200);
static int count;
cout << “count in a ;” << a.count;
public:
cout << “count in b ;” << b.count;
Dummy (int I, int j) {
x = i; return 0;
y = j; }
count++;
}
}
int Dummy::count = 0;
Output is
count in a : 2
count in b : 2
Both the objects have same value
67. 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
68. // class with static member function
class 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;
69. 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 ::
70. 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);
71. 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.
72. • 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.
73. 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.
74. 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
}
75. // class const variable member - Example
class Employee {
const int id;
int age;
public:
Employee (int I, int j) : id (i) { // Initialize
age = j; // Assignment
}
void set_values (int i, int j) {
id = i; // Compilation Error
age = 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.
76. 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.
77. • 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
78. • 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.
79. 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.