You are on page 1of 41

Classes and Objects: Part-I

Department of Computer Science and Engineering


School of Engineering and Technology
Kaziranga University
Jorhat-785006, Assam.
monowar@kazirangauniversity.in
Classes and Objects

Classes are basic constructs of C++


for creating user defined data types.
Class
Consists of both data and methods
Defines properties and behavior of a set of
entities
Object
An instance of a class
A variable identified by a unique name

2
M. H. Bhuyan Lec 9, 10 and 11
Classes and Objects
Classes are extension of structures.
It makes possible encapsulation, data hiding and inheritance
Difference:
all members of a structure are public by default.
where as all members of a class are private by default.

3
M. H. Bhuyan Lec 9, 10 and 11
Define a Class Type

Header class Rectangle


class class_name {
{ private:
permission_label:
int width;
member;
Body
int length;
permission_label:
member; public:
... void set(int w, int l);
}; int area();
};
4
M. H. Bhuyan Lec 9, 10 and 11
Creating Objects
Syntax is:
class_name object_name;

For example,
Rectangle r1, r2;

5
M. H. Bhuyan Lec 9, 10 and 11
Class Definition Member Functions
Used to
access the values of the data members (accessor)
perform operations on the data members (implementor)
Are declared inside the class body, in the same way as declaring
a function
Their definition can be placed inside the class body, or outside
the class body
Can access both public and private members of the class
Can be referred to using dot or arrow member access operator

6
M. H. Bhuyan Lec 9, 10 and 11
Define a Member Function

class Rectangle
{
private:
int width, length;
class name
public:
void set (int w, int l);
int area() {return width*length; } member function name

};

void Rectangle :: set (int w, int l)


inline {
r1.set(5,8);
width = w;
rp->set(8,10); length = l;
scope operator
}
7 7
M. H. Bhuyan Lec 9, 10 and 11
Accessing class Members

Class members can be accessed using the objects.


Objects must use member access operator, the dot(.)

Syntax: ObjectName.DataMember

Data Member can be variable or function.


Should be public to be accessible.
objectName.function_Name( actual parameters)
Example, s1.name;
// cannot be accessed -> data hiding if private
S1.gatdata();

8
M. H. Bhuyan Lec 9, 10 and 11
Class Definition - Access Control
Information hiding
To prevent the internal representation from direct access from outside the
class
Access Specifiers
public
may be accessible from anywhere within a program

private
may be accessed only by the member functions, and friends of this class, not open for
nonmember functions

protected
acts as public for derived classes (virtual)
behaves as private for the rest of the program

Difference between classes and structs in C++


the default access specifier is private in classes
the default access specifier is public in structs

9
M. H. Bhuyan Lec 9, 10 and 11
Class Definition - Access Control
The default access specifier is private
The data members are usually private or protected
A private member function is a helper, may only be accessed by another
member function of the same class (exception friend function)
The public member functions are part of the class interface
Each access control section is optional, repeatable, and sections may occur
in any order

10
M. H. Bhuyan Lec 9, 10 and 11
Private Member Functions
A private member function can only be called by another function that is
member of its class.
For example,
class privateTest{
int m;
void read();
public:
void update();
void write();
};

privateTest t1;
t1.read();

void privateTest:: update(){


read();
}
11
M. H. Bhuyan Lec 9, 10 and 11
Static Data Members
A data member of a class can be qualified as static.
- It is initialized to zero when the first object of its class is created. No
other initialization is permitted.
- Only one copy of member function is created for the entire class and is
shared by all objects of that class.
- It is visible only within the class but its lifetime is entire program.

12
M. H. Bhuyan Lec 9, 10 and 11
Example

#include<iostream>
using namespace std;
class staticDMTest{
static int p;
int q;
public:
void inputData(int a)
{ q=a; p++;}
void getCount()
{cout<<Count = <<p<<endl;}
};
13
M. H. Bhuyan Lec 9, 10 and 11
Example
int staticDMTest :: p;
int main()
{
staticDMTest d, e;
d.getCount();
e.getCount();
d.inputData(100);
e.inputData(200);
d.getCount();
e.getCount();
retrun 0;
}

14
M. H. Bhuyan Lec 9, 10 and 11
Static Member Functions
A member function that is declared as static known as static
member function.
Following are some properties:
- A static function can have access to only other static members
(functions or variables).
- A static member function can be called using the class name.
- Syntax:
class-name:: function name

15
M. H. Bhuyan Lec 9, 10 and 11
Example

#include<iostream>
using namespace std;
class staticFMTest{
static int p;
int q;
public:
void inputData(int a)
{ q=a; p++;}
static void getCount()
{cout<<Count = <<p<<endl;}
};
16
M. H. Bhuyan Lec 9, 10 and 11
Example
int staticFMTest :: p; // static data member
int main()
{
staticFMTest d, e;
d.getCount();
e.getCount();
staticFMTest :: getCount(); // static function member
d.inputData(100);
e.inputData(200);
staticFMTest :: getCount();
d.getCount();
e.getCount();
retrun 0;
}

17
M. H. Bhuyan Lec 9, 10 and 11
Arrays of Objects
Array variable of class type is known as array of objects.
For example,
Employee manager[5];

18
M. H. Bhuyan Lec 9, 10 and 11
Problems
Write a program in C++ to implement array of objects for an
employee of an organization.

Create a class MAT in C++ of size m x n. Define all possible matrix


operations for MAT type objects.
[Operations: addition, subtraction, multiplication, transpose]

19
M. H. Bhuyan Lec 9, 10 and 11
Friend Function and Friend Class
Friend class can access private and protected members of another class
friend functions are not member functions of a class
Defined outside of class scope
Properties
Friendship is granted, not taken
NOT symmetric (if B a friend of A, A not necessarily a friend of B)
NOT transitive (if A a friend of B, B a friend of C, A not necessarily a
friend of C)

20
M. H. Bhuyan Lec 9, 10 and 11
Friend Function and Friend Class
friend function
Keyword friend before function prototype in class that is giving friendship.
friend int myFunction(int x);
Appears in the class granting friendship
friend class
Type friend class Classname in class granting friendship
If ClassOne granting friendship to ClassTwo,
friend class ClassTwo;
appears in ClassOne's definition

21
M. H. Bhuyan Lec 9, 10 and 11
Example : Friend Function
#include <iostream>
using namespace std;
class friendTest {
int a, b;
public:
friend int sum(friendTest x);
void set_ab(int i, int j);
};
void myclass::set_ab(int i, int j)
{ a = i; b = j; }
// Note: sum() is not a member function of any class.
int sum(friendTest x)
{/* Because sum() is a friend of friendTest, it can directly access a
and b. */
return x.a + x.b; }
22
M. H. Bhuyan Lec 9, 10 and 11
Example : Friend Function
int main()
{ friendTest n;
n.set_ab(3, 4);
cout << sum(n);
return 0;
}

23
M. H. Bhuyan Lec 9, 10 and 11
Example : Friend Class
// Using a friend class.
#include <iostream>
using namespace std;
class TwoValues {
int a; int b;
public:
TwoValues(int i, int j) { a = i; b = j; }
friend class Min;
};
class Min { public: int min(TwoValues x); };
int Min::min(TwoValues x) {
return x.a < x.b ? x.a : x.b; }
24
M. H. Bhuyan Lec 9, 10 and 11
Example: Friend Class
int main() {
TwoValues ob(10, 20);
Min m;
cout << m.min(ob);
return 0;
}

25
M. H. Bhuyan Lec 9, 10 and 11
Friend Function and Friend Class

A friend function has the following advantages


Provides additional functionality which is kept outside the class.
Provides functions that need data which is not normally used by
the class.
Allows sharing private class information by a non-member
function.
A friend function has the following disadvantage
They dont allow dynamic binding.
Friend functions are not inherited.
They add to the global namespace.

26
M. H. Bhuyan Lec 9, 10 and 11
Friend Function and Friend Class
Friend classes are useful when a class wants hide features from users
that are needed only by another, tightly coupled class.
Friend classes also arise when a member function on a class needs to
maintain state between calls and when multiple copies of this state
must exist.

27
M. H. Bhuyan Lec 9, 10 and 11
Constructors

The main use of constructors is to initialize objects.


The function of initialization is automatically carried out
by the use of a special member function called a
constructor.
Constructor is a special member function that takes the
same name as the class name.
The syntax generally is as given below:
<class name> ( arguments);
The default constructor for a class A has the form
A::A()
28
M. H. Bhuyan Lec 9, 10 and 11
Types of Constructors
The constructor is automatically called when an object
is created.
There are three forms of constructors namely:
Default constructor
Parameterized constructors
Copy constructor

29
M. H. Bhuyan Lec 9, 10 and 11
Default Constructors
The constructor has no arguments in it.
Default Constructor is also called as no argument constructor.
For example:
class A
{ private: int a;
public: A() // A() is the constructor
{ cout<<Constructor is called"; }
};
int main()
{
A obj;
return 0; }

30
M. H. Bhuyan Lec 9, 10 and 11
Parameterized Constructors
A parameterized constructor is just one that has parameters
specified in it.
We can pass the arguments to constructor function when
object are created.
A constructor that can take arguments are called parameterized
constructors.

31
M. H. Bhuyan Lec 9, 10 and 11
Parameterized Constructors

For example:
class A
{ private: int a;
public: A(int b) // A() is the constructor
{ a=b;
cout<<Constructor is called<<a; }
};
int main()
{
A obj(5);
return 0; }
32
M. H. Bhuyan Lec 9, 10 and 11
Copy Constructors
Copy constructor is used to declare and initialize an object from
another object.
For example:
abc c2(c1);
would define the object c2 and at the same time initialize it to the
value of c1.
The process of initializing through a copy constructor is known as
copy initialization.

33
M. H. Bhuyan Lec 9, 10 and 11
Example
class abc { int a, b;
public:
abc(int x, int y) {
a = x;
b = y;
}
abc::abc(abc &p)
{
a = p.a;
b = p.b;
}

34
M. H. Bhuyan Lec 9, 10 and 11
Contd..
void showdata() {
cout << a << " " << b << endl; }
};
int main() {
abc c1(10, 20);
abc c2(c1);
c1.showdata();
c2.showdata();
return 0;
}

35
M. H. Bhuyan Lec 9, 10 and 11
Constructors
Automatically called when an object is created.
We can define our own constructors
A constructor takes the same name as the class name.
We cant define a constructor in the private access modifier.
No return type is specified for a constructor.
Constructor must be defined in the public. The constructor must be
a public member.
Overloading of constructors is possible.
If an object is copied from another object then the copy constructor
is called.

36
M. H. Bhuyan Lec 9, 10 and 11
Destructors
Destructors are special member functions defined in the public
access modifier
Release dynamic allocated memory.
Destructors are automatically named.
Syntax:
~ classname();
Take the same name as class name.
Destructors cannot be overloaded.
No return type is specified.

37
M. H. Bhuyan Lec 9, 10 and 11
Example
#include<iostream>
using namespace std;
class Line {
public:
int getLength( void );
Line( int len ); // simple constructor
Line( const Line &obj); // copy constructor
~Line(); // destructor
private:
int *ptr;
}; // Member functions definitions including constructor
Line::Line(int len) {
cout << "Normal constructor allocating ptr" << endl;
// allocate memory for the pointer;
ptr = new int;
*ptr = len;
}
38
M. H. Bhuyan Lec 9, 10 and 11
Contd..
Line::Line(const Line &obj)
{ cout << "Copy constructor allocating ptr." << endl;
ptr = new int;
*ptr = *obj.ptr; // copy the value
}
Line::~Line(void)
{ cout << "Freeing memory!" << endl;
delete ptr; }
int Line::getLength( void )
{ return *ptr; }
void display(Line obj)
{ cout << "Length of line : " << obj.getLength() <<endl; }
// Main function for the program
int main( )
{ Line line(10);
display(line);
return 0;
}
39
M. H. Bhuyan Lec 9, 10 and 11
Problems
Write a class to represent a bank account. Include the
following members:
data members
1. Name of the depositor
2. Account number
3. Type of account
4. Balance amount in the account
Member functions
1. To assign initial values
2. To deposit an account
3. To withdraw an amount after checking the balance
4. To display name and balance
40
M. H. Bhuyan Lec 9, 10 and 11
Questions?

41
M. H. Bhuyan Lec 9, 10 and 11

You might also like