Vous êtes sur la page 1sur 23

Unit II

Chapter 2: Classes and Objects

2.1 Class declarations


A class is a way to bind the data and its associated function together. It
allows the data and functions to be hidden, if necessary, from external use. When
defining a class, we are creating a new abstract data type that can be treated like
any other built-in data type. Generally, a class specification has two parts:
• Class Declaration.
• Class function definitions

The class declaration describes the type and scope of its members. The class
function definitions describe how the functions are implemented.
The general form of a class declaration is:

Class Class_name
{
private:
variable declarations;
function declarations;
public:
variable declarations;
function declarations;
};

The class declaration is similar to a struct declaration. The keyword class specifies
that what follows is an abstract data of type class_name. The body of class is
enclosed within braces and terminated by a semicolon. The class body contains the
declaration of variables and functions. These functions and variables are
collectively known as class members. They are usually grouped under two
sections, namely, private and public to denote which are the members are private
and which of them are public.

A Simple Class example

class student
{
int r_no; //variable declaration
char name; //private by default
public:
void getdata (int a, float b); //functions declaration
void putdata (void); //using prototype
};

2.2 Object and declaration


A class provides the blueprints for objects, so basically an object is created
from a class. We declare objects of a class with exactly the same sort of declaration
that we declare variables of basic types. Following statements declare two objects
of class Box:

Box Box1; // Declare Box1 of type Box


Box Box2; // Declare Box2 of type Box

Both of the objects Box1 and Box2 will have their own copy of data members.

2.2.1 Accessing the Data Members:


The public data members of objects of a class can be accessed using the direct
member access operator (.). Let us try the following example to make the things
clear:
#include <iostream>
using namespace std;
class Box
{
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

int main( )
{
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here

// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;
// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;
// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}

When the above code is compiled and executed, it produces the following result:

Volume of Box1 : 210


Volume of Box2 : 1560

It is important to note that private and protected members cannot be accessed


directly using direct member access operator (.).

2.3 Constant objects


Constant is something that doesn't change. In C and C++ we use the keyword const
to make program elements constant. Const keyword can be used in many context
in a C++ program. Const keyword can be used with:

• Variables
• Pointers
• Function arguments and return types
• Class Data members
• Class Member functions
• Objects
When an object is declared or created with const, its data members can never be
changed, during object's lifetime.

Syntax:
const class_name object;
#include <iostream>
#include <string>
using namespace std;
class X
{
int i;
public:
X(int x)
{ i=x; }
int f() const
{ i++; }
int g()
{ i++; }
};

int main()
{
X obj1(10);
const X obj2(20); // Const Object
obj1.f();
obj2.f();
cout << obj1.i << obj2.i ;
obj1.g();
obj2.g();
}

Output will be:

p1.x = 10, p1.y = 15


p2.x = 10, p2.y = 15

Here, const member function never changes data members of class, and it can be
used with both const and non-const object. But a const object can't be used with a
member function which tries to change its data members.

2.4 Pointers to objects


A variable that holds an address value is called a pointer variable or simply pointer.
Pointer can point to objects as well as to simple data types and arrays. C++ allows
you to have pointers to objects. A pointer can also point to an object created by a
class. Just like other pointers, the object pointers are declared by placing in front of
a object pointer's name. It takes the following general form:

class-name ∗ object-pointer ;

where class-name is the name of an already defined class and object-pointer is the
pointer to an object of this class type. For accessing normal data members we use
the dot (.) operator with object and (->) with pointer to object.

#include <iostream>
#include <string>
using namespace std;
class Data
{
public:
int a;
void print()
{
cout << "a is="<< a;
}
};
int main()
{
Data d, *dp;
dp = &d; // pointer to object
int Data::*ptr=&Data::a; // pointer to data member 'a'
d.*ptr=10;
d.print();
dp->*ptr=20;
dp->print();
}
Output will be:
p1.x = 10, p1.y = 15
p2.x = 10, p2.y = 15

2.5 Structures
Structure is the collection of variables of different types under a single name for better
visualisation of problem. Arrays is also collection of data but arrays can hold data of only one
type whereas structure can hold data of one or more types.

2.5.1 Definition of structure in C++


The struct keyword defines a structure type followed by an identifier (name of the
structure). Then inside the curly braces, you can declare one or more members
(declare variables inside curly braces) of that structure. When a structure is created,
no memory is allocated. The structure definition is only the blueprint for the
creating of variables. For example:

struct employee {
char name[50];
int age;
float salary;
};

The keyword struct declares employee as a new data type that can hold three fields
of different data type. The fields are known as Structure members or elements. The
identifier employee, which is referred to as structure name or structure tag, can be
used to create variable of type employee. For example:

Struct employee A;

A is variable of type employee and has three member variables as defined by the
template. Member variables can be accessed using the dot(.) operator. For
Example:

Strcpy(A.name,”john”)

Unit II
Chapter 3: Functions
3.1 Access functions

Data hiding is one of the important features of Object Oriented Programming


which allows preventing the functions of a program to access directly the internal
representation of a class type. The access restriction to the class members is
specified by the labelled public, private, and protected sections within the class
body. The keywords public, private, and protected are called access specifiers.

A class can have multiple public, protected, or private labelled sections. Each
section remains in effect until either another section label or the closing right brace
of the class body is seen. The default access for members and classes is private.

class Base
{
public:
// public members go here
protected:
// protected members go here
private:
// private members go here
};
A public member variable or function can be accessed anywhere in the program, or
even viewed from outside the class.

A protected member variable or function can be accessed in the class where it is


declared and very next derived class. After that their scope is ended.

A private member variable or function cannot be accessed, or even viewed from


outside the class. Only the class and friend functions can access private members.

3.1.1 Defining member functions:


Member functions can be defined in two places:
• Outside the class definition.
Member functions that are declared inside the class have to be defined
separately outside the class. Their definitions are very much like the normal
functions. They should have the function header and a function body.
An important difference between a member function and a normal function is
that a member function incorporates a membership “identity lebel” in the
header. This lebel tells the compiler which class function belongs to. They may
be coded as follows:
void item::getdata(int a, float b)
{
number=a;
cost=b;
}

• Inside the class definition.


Another method of defining a member function is to replace the function
declaration by the actual function definition inside the class. It may be coded as
follows:
Class item
{
Int number;
Float cost;
Public:
getdata(int a, float b) //definition inside the class
{
number=a;
cost=b;
}
};
When a function is defined inside a class, it is treated as inline function.
Normally, only small functions are defined inside the class definition.

3.2 Private member functions


It is normal practice to place all the data items in a private section and all the
functions in public, but some situations may require certain functions to be hidden
from the outside calls. Then these functions can be placed in private section.

A private member function can only be called by another function that is member
of its class. Even an object cannot invoke a private function using (.) operator.
Consider the following example:
class sample
{
int m;
void read(void);
public:
void update(void);
void write(void);
};

The function read() is private member function it can be called outside the class by
the function update() which is public member of the same class.

void sample::update(void)
{
read();
}

3.3.Static data members


A data member of a class can be qualified as static. The properties of a
static member variable are similar to that of a C static variable. A static
member variable has certain special characteristics. These are:

• It is initialized to zero when the first object of its class is created. No


other initialization is permitted.

• Only one copy of that member is created for the entire class and is shared
by all the objects of that class, no matter how many objects are created.

• It is visible only within the class, but its lifetime is entire program.

Static variables are normally used to maintain values common to the entire
class, a static data member can be used as a counter that records the
occurrences of all the objects.

3.4 Static function members

By declaring a function member as static, you make it independent of any


particular object of the class. It has the following properties:
• A static member function can be called even if no objects of the class exist and
the static functions are accessed using only the class name and the scope
resolution operator (::).
• A static member function can only access static data member, other static
member functions and any other functions from outside the class.

Static member functions have a class scope and they do not have access to the “this
pointer” of the class. You could use a static member function to determine whether
some objects of the class have been created or not.

The concept of static function members can be seen in following example:

#include <iostream>
using namespace std;
class Box
{
public:
static int objectCount;
// Constructor definition
Box(double l=2.0, double b=2.0, double h=2.0)
{
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
// Increase every time object is created
objectCount++;
}
double Volume()
{
return length * breadth * height;
}
static int getCount()
{
return objectCount;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

// Initialize static member of class Box


int Box::objectCount = 0;
int main(void)
{
// Print total number of objects before creating object.
cout << "Inital Stage Count: " << Box::getCount() << endl;
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
// Print total number of objects after creating object.
cout << "Final Stage Count: " << Box::getCount() << endl;
return 0;
}

When above code is compiled and executed, produces the following result:

Inital Stage Count: 0


Constructor called.
Constructor called.
Final Stage Count: 2

Chapter 4: Constructor and Destructor

4.1 Constructors
A class constructor is a special member function of a class that is executed
whenever we create new objects of that class.

A constructor will have exact same name as the class and it does not have any
return type at all, not even void. Constructors can be very useful for setting
initial values for certain member variables.

Following example explains the concept of constructor:


#include <iostream>
using namespace std;
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor

private:
double length;
};

// Member functions definitions including constructor


Line::Line(void)
{
cout << "Object is being created" << endl;
}

void Line::setLength( double len )


{
length = len;
}
double Line::getLength( void )
{
return length;
}
// Main function for the program
int main( )
{
Line line;
// set line length
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
return 0;
}
This code will produces the following result:

Object is being created


Length of line: 6
4.2 Constructor initialization lists
Constructor is a special non-static member function of a class that is used to
initialize objects of its class type. whenever an object of a class is created, its
constructor is called.

Initializer List is used to initialize data members of a class. The list of


members to be initialized is indicated with constructor as a comma separated
list followed by a colon. Following is an example that uses initializer list to
initialize x and y of Point class.

#include<iostream>
using namespace std;
class Point {
private:
int x;
int y;
public:
Point(int i = 0, int j = 0):x(i), y(j) {}
/* The above use of Initializer list is optional as the constructor can also
be written as:
Point(int i = 0, int j = 0) {
x = i;
y = j;
} */
int getX() const {return x;}
int getY() const {return y;}
};
int main() {
Point t1(10, 15);
cout<<"x = "<<t1.getX()<<", ";
cout<<"y = "<<t1.getY();
return 0;
}
Output will be
x = 10, y = 15

The above code is just an example for syntax of Initializer list. In the above
code, x and y can also be easily initialize inside the constructor.
4.3 The copy constructor
A copy constructor is a member function which initializes an object using
another object of the same class. A copy constructor has the following general
function prototype:
In C++, a Copy Constructor may be called in following cases:
1.When an object of the class is returned by value.
2. When an object of the class is passed (to a function) by value as an
argument.
3. When an object is constructed based on another object of the same class.
4. When compiler generates a temporary object.
If we don’t define our own copy constructor, the C++ compiler creates a
default copy constructor for each class which does a member wise copy
between objects. The compiler created copy constructor works fine in general.
#include<iostream>
using namespace std;
class Point
{
private:
int x, y;
public:
Point(int x1, int y1)
{
x = x1; y = y1;
}
// Copy constructor
Point(const Point &p2)
{
x = p2.x; y = p2.y;
}
int getX()
{
return x;
}
int getY()
{
return y;
}
};

int main()
{
Point p1(10, 15); // Normal constructor is called here
Point p2 = p1; // Copy constructor is called here
// Let us access values assigned by constructors
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();
return 0;
}

Output will be:


p1.x = 10, p1.y = 15
p2.x = 10, p2.y = 15

4.4 The class destructor


Destructor is a special class function which destroys the object as
soon as the scope of object ends. The destructor is called
automatically by the compiler when the object goes out of scope.

The syntax for destructor is same as that for the constructor; the
class name is used for the name of destructor; with a tilde (~) sign as
prefix to it.
#include<iostream>
using namespace std;
class A
{
public:
A()
{
cout << "Constructor called\n";
}

~A()
{
cout << "Destructor called\n";
}
};

int main()
{
A obj1; // Constructor Called
int x=1;
if(x)
{
A obj2; // Constructor Called
} // Destructor Called for obj2
} // Destructor called for obj1

Output will be:

Constructor called
Constructor called
Destructor called
Destructor called

2.1 Passing Objects as an argument


The objects of a class can be passed as arguments to member functions as well as nonmember
functions either by value or by reference. When an object is passed by value, a copy of the actual
object is created inside the function. This copy is destroyed when the function terminates.
Moreover, any changes made to the copy of the object inside the function are not reflected in the
actual object. On the other hand, in pass by reference, only a reference to that object (not the
entire object) is passed to the function. Thus, the changes made to the object within the function
are also reflected in the actual object.
Whenever an object of a class is passed to a member function of the same class, its data members
can be accessed inside the function using the object name and the dot operator. However, the
data members of the calling object can be directly accessed inside the function without using the
object name and the dot operator.

2.2 Returning objects from function


A function can also return objects either by value or by reference. When an object is returned by
value from a function, a temporary object is created within the function, which holds the return
value. This value is further assigned to another object in the calling function.

The syntax for defining a function that returns an object by value is


class_name function_name (parameter_list)
{
// body of the function
}

To understand the concept of returning an object by value from a function, consider this
example.

#include<iostream.h>
class weight
{
int kilogram;
int gram;
public:
void getdata ();
void putdata ();
void sum_weight (weight,weight) ;
weight sum_weight (weight) ;
};
void weight :: getdata()
{
cout<<"/nKilograms:";
cin>>kilogram;
cout<<"Grams:";
cin>>gram;
}
void weight :: putdata ()
{
cout<<kilogram<<" Kgs. and"<<gram<<" gros.\n";
}
weight weight :: sum_weight(weight w2)
{
weight temp;
temp.gram = gram + w2.gram;
temp.kilogram=temp.gram/1000;
temp.gram=temp.gram%1000;
temp.kilogram+=kilogram+w2.kilogram;
return(temp);
}
int main ()
{
weight w1,w2 ,w3;
cout<<"Enter weight in kilograms and grams\n";
cout<<"\n Enter weight 1" ;
w3=w1.sum_weight (w2);
wl.getdata();
cout<<" \n Enter weight 2" ;
w2.getdata();
w3.sum_weight(wl,w2);
cout<<"/n Weight 1 = ";
wl.putdata();
cout<<"Weight 2 = ";
w2.putdata();
cout<<"Total Weight = ";
w3.putdata();
return 0;
}

As the return type of function is weight (an object of class weight), a temporary object temp is
created within the function for holding return values. These values are accessed as temp
kilogram and temp gram by the function. When the control returns to main (), the object temp is
assigned to the object w3 in main().
Figure represents accessing of member variables within the function and returning a result from
the temporary object.

2.3 Friend function

A friend function is a function that can access the private members of a class as though it were a
member of that class. In all other regards, the friend function is just like a normal function. A
friend function may be either a normal function, or a member function of another class. To
declare a friend function, simply use the friend keyword in front of the prototype of the function
you wish to be a friend of the class. It does not matter whether you declare the friend function in
the private or public section of the class.
Features
A friend function is not in the scope of the class, in which it has been declared as friend.
• It cannot be called using the object of that class.
• It can be invoked like a normal function without any object.
• Unlike member functions, it cannot use the member names directly.
• It can be declared in public or private part without affecting its meaning.
• Usually, it has objects as arguments.

Here’s an example of using a friend function:


class Accumulator
{
private:
int m_value;
public:
Accumulator()
{
m_value = 0;
}
void add(int value)
{
m_value += value;
}
friend void reset(Accumulator &accumulator);
};

void reset(Accumulator &accumulator)


{
accumulator.m_value = 0;
}

int main()
{
Accumulator acc;
acc.add(5); // add 5 to the accumulator
reset(acc); // reset the accumulator to 0
return 0;
}

In this example, we’ve declared a function named reset() that takes an object of class
Accumulator, and sets the value of m_value to 0. Because reset() is not a member of the
Accumulator class, normally reset() would not be able to access the private members of
Accumulator. However, because Accumulator has specifically declared this reset() function to be
a friend of the class, the reset() function is given access to the private members of Accumulator.

Note that we have to pass an Accumulator object to reset(). This is because reset() is not a
member function. It does not have a *this pointer, nor does it have an Accumulator object to
work with, unless given one.
2.4 Friend classes
It is also possible to make an entire class a friend of another class. This gives all of the members
of the friend class access to the private members of the other class. Here is an example:
class Storage
{
private:
int m_nValue;
double m_dValue;
public:
Storage(int nValue, double dValue)
{
m_nValue = nValue;
m_dValue = dValue;
}
// Make the Display class a friend of Storage
friend class Display;
};

class Display
{
private:
bool m_displayIntFirst;

public:
Display(bool displayIntFirst)
{
m_displayIntFirst = displayIntFirst;
}

void displayItem(Storage &storage)


{
if (m_displayIntFirst)
std::cout << storage.m_nValue << " " << storage.m_dValue << '\n';
else // display double first
std::cout << storage.m_dValue << " " << storage.m_nValue << '\n';
}
};

int main()
{
Storage storage(5, 6.7);
Display display(false);
display.displayItem(storage);
return 0;
}

Because the Display class is a friend of Storage, any of Display’s members that use a Storage
class object can access the private members of Storage directly. This program produces the
following result:
6.7 5

2.5 Array of pointers to objects


Instead of using one pointer to an object, you can declare an array of pointers to object. The
syntax used is:
ClassName *VariableName[Dimension];

The ClassName must be an existing object. You can use your own object or one that shipped
with the compiler. After the asterisk operator, type a valid name for a C++ variable. The
dimension, which is (an estimate of) the number of elements of the array, is included in square
brackets.
After declaring the variable, you can initialize each member of the array using the new operator.
This operator allocates enough memory space for the member of the array. This means that the
initialization with the new operator can be followed by an actual initialization of the member
variables of the array.
To initialize a member of the array, you have various options. You must first call the new
operator for each member of the array. Once again, you can use one of the constructors. Consider
the above Cone object. We saw that one of its constructors took two arguments to create an
object. You can use such a constructor to initialize a member of the array.

2.6 Default Constructors


A default constructor is a constructor which can be called with no arguments (either defined with
an empty parameter list, or with default arguments provided for every parameter).
Syntax :
class_name ()
{
Constructor Definition
}
Example :
class Cube
{
int side;
public:
Cube()
{
side=10;
}
};
int main()
{
Cube c;
cout << c.side;
}

Output :
10

In this case, as soon as the object is created the constructor is called which initializes its data
members.
A default constructor is so important for initialization of object members, that even if we do not
define a constructor explicitly, the compiler will provide a default constructor implicitly.
class Cube
{
int side;
};

int main()
{
Cube c;
cout << c.side;
}

Output : 0
In this case, default constructor provided by the compiler will be called which will initialize the
object data members to default value, that will be 0 in this case.
2.7 Parameterised constructors
These are the constructors with parameter. Using this Constructor you can provide different
values to data members of different objects, by passing the appropriate values as argument.

Example :
class Cube
{
int side;
public:
Cube(int x)
{
side=x;
}
};

int main()
{
Cube c1(10);
Cube c2(20);
Cube c3(30);
cout << c1.side;
cout << c2.side;
cout << c3.side;
}

OUTPUT : 10 20 30
By using parameterized constructor in above case, we have initialized 3 objects with user defined
values. We can have any number of parameters in a constructor.

Vous aimerez peut-être aussi