Classes
&
Objects
Structures in C
• Structures (user-defined data type) provide a method for packing
together data of different types.
• Once the structure is defined, we can create the variables of that type
using declarations similar for the in-built data types.
struct student {//struct is a keyword, student is structure name
char name[20]; //structure members or elements
int roll_no;
float marks;
}; struct student A; //A is a variable of type structure
strcpy(A.name, “John”);
A.roll_no = 999; //member variable access using . operator
Final_total = A.marks + 5;
Limitations of Structures in C
• We can not treat the struct data types like in-built data types. E.g.
struct complex c1,c2,c3; // used to assign value using dot operator
then c3=c2+c1; //is illegal
• No Data Hiding: Structure members can be directly accessed by the
structure variable by any function anywhere in their scope i.e., structure
members are public members.
• The statements for declaring variables in C is like
struct student s1;
• But in C++ we can write like
student s1; // this is an error in C
• C++ structures can have both variables and functions as members. It can
also declare some of its member as ‘private’ (to facilitate data hiding) so
that it cannot be accessed by the external functions.
Specifying a Class
• Class is a blueprint about an entity that bind the data and its
associated functions together.
• It is an Abstract Data Type (custom type made by programmer) can
be treated like any other in-built data type.
• Class Specification has two parts: 1. Class declaration, 2. Class
function definitions
– <class> <class_name> {
private: (default)
variable declaration; function declaration; \\member
public: (called visibility level)
variable declaration; function declaration;
protected: (inherit by child)
variable declaration; function declaration;
};
Class Example
• class item {
int number; //variable declaration
float cost; // private by default
public:
void getdata (int a, float b); // function x
void put data (void); // using prototype
}; //ends with semicolon
Data Hiding in Classes
class
Private Area
No entry to Data
Private area Functions
Public Area
Data
Entry allowed Functions
to Public area
• Hence using a class keyword, we can create the new data
type. This data type has the data and functions.
• Normally data declaration is kept in the private section,
and the functions are declared in the public section.
• The private data can be accessed by the member function of
that class only.
Creating Class Objects
• Object is a real entity created based on class specification.
• The declaration of the objects is similar to the variables of the basic
data type.
item x, y, z; //
• Class declaration does not allocate any memory space for the
objects. The memory space to the objects is allocated at the time of
declaration of objects. E.g., item x,y,z;
• Objects can also be created at the time of class declaration. Like;
class item{
::::::::::::
} x,y,z,;
• This practice is not followed so that the declaration of the objects is
near to the place of their use.
Accessing Class Members
• The private data of a class can be accessed only through the
member functions of that class.
• Following format is used to call the member function
<object-name>.<function-name>(actual-arguments);
e.g., x.getdata(100,76.8);
• Following statements are wrong statements:
getedata(100,76.8);
or x.number=100;
• Objects communicate with each others by sending and receiving
messages. This is achieved through the member functions. (Refer
Slide 21). Objects communicate by passing themselves (or their
data) to each other’s functions.
Defining Member Functions
• Member Functions can be defined in two places:
1. Outside the class definition
2. Inside the class definition
• Function Definition Outside the Class definition: The function is
defined like a normal function, the only difference is that it will have
membership label ‘identity label (::)’ in the header. This tells the
compiler that to which class the function belongs to:
<return-type> <class-name> :: <function-name>(argument
declaration)
{
function body
}
Cont.
• Different classes can have the same function name, where the
membership label will resolve the scope.
• Member Functions can access the private data of the classes, but the
normal functions cannot do so (doesn’t belong to the class).
• A member function can call another member function without using
the dot operator.
Function Definition Inside the Class Definition:
• Here in this case the function declaration is replaced by the function
definition inside the class.
• Whenever the function is defined inside the class it is treated as an
inline function. Hence all the restrictions applicable on the inline
functions are also applicable on these functions.
• Normally only the small functions are defined inside the class
definition.
Example Program
#include<iostream.h>
using namespace std; void item::getdata(int a, float b)
//use membership label
class item
{
{ number = a;
int number; //private by default cost = b;
float cost; }
public: int main()
{
void getdata(int a, float b);
item x; // create object x
//prototype declaration
cout<<"\object x"<<"\n";
void putdata(void) //def. inside x.getdata(100,299.95);
class x.putdata();
{ item y;
cout<<"Number:"<<number<<"\n"; cout<<"object y"<<"\n";
cout<<"Cost:"<<cost <<"\n"; y.getdata(200,175.5);
y.putdata();
}
return 0;
} ; }
Making an Outside Function Inline
• It is always good practice to define the member functions outside
the class definition.
• Even while defining the function outside the class, we can make the
function inline.
– class item
{
::::::::::
public:
void getdata(int a, float b);
};
inline void item::getdata(int a, float b)
{ number = a;
cost = b;
}
Nesting of Member Functions
• We can call a member function of a class by the object of that class.
• Another way to access the member function is that we can call that function
inside another member function, called “Nesting of Member Functions”
#include <iostream> else
using namespace std; return(n);
class set }
void set::input(void)
{ {
int m,n; cout<<"Input values of m & n"<<"\n";
public: cin>>m>>n;
}
void input(void); void set::display(void)
void display(void); {
int largest(void); cout<<"Largest Value = "<<largest()<<"\n";
}
}; int main()
int set::largest(void) {
{ set A;
A.input();
if (m>=n) A.display();
return (m); return 0;
}
Private Member Functions
• There are some situations that requires certain functions to be
hidden from outside calls. Tasks such as deleting an account, or
providing increment to an employee these tasks should have
restricted access.
class sample
{ void sample::update(void)
int m; {
void read(void); //private member read(); //no object used
}
public:
void update(void);
void write(void);
};
s1.read(); \\ won’t work, object
\\ cannot access private
\\ member
Arrays within a class
• Arrays can be used as member variable in a class.
– const int size = 10; //providing value for array size
class array
{
int a[size];
public:
void setval(void);
void display(void);
}
• The member array variables can be used as a normal variables.
Static Data Members and Member
Function
• The class members (data member and member function) can be
defined as:
– Static:
a. Variable: Maintain values common to the entire program.
Means there is only one copy of the variables, shared by all
objects of that class.
b. Member Function: A method that can be used without an
object and can directly be used using a class name with scope
resolution operator.
– Non-static:
a. Variable: Each object maintain their own copy of variables.
b. Member Function: A members that always need an object or
instance to use them
Static Data Member
#include <iostream>
using namespace std; int item::count; //allocate memory
class item int main()
{
{ item a,b,c; //count is initialized to
static int count; zero
int number; a.getcount();
public: b.getcount();
void getdata(int a) c.getcount();
{ a.getdata(100);
number = a; b.getdata(200);
count++; c.getdata(300);
}
void getcount(void) cout<<"After Reading Data"<<"\n";
a.getcount();
{ b.getcount();
cout<<"count:"; c.getcount();
cout<<count<< "\n"; return 0;
} }
};
Static Member Function
#include <iostream> static long factorial (int n)
using namespace std; {
if (n ==1)
class Number
return 1;
{ else
private: return n *factorial(n-1);
int num; }
public: };
int main()
long factorial () //non-static
{
{ Number x(5);
long f = 1; cout<<“Factorial of 5
int i; is:"<<x.factorial()"\n";
for (i = 1;i<=num;i++) cout<<“Factorial of 7 is:”
<<Number::factorial(7);
f = f*i;
return 0;
return f; }
}
Array of Objects
• We know that class is a data type, and the object is a variable of
class. Hence, we can have an array of variables of class type called
array of objects.
– class employee
{
char name[30];
float age;
public:
void getdata(void);
void putdata(void);
};
employee manager[3]; //array of manager manager[0]. manager[1],
manager [2].putdata();
employee clerk[15];
employee worker[75];
Protected Access Specifier
• Protected is a visibility modifier, that serves a limited purpose in
inheritance.
• A member declared as protected can be accessed by the member
functions of that class and the functions in a class immediately
derived from it.
• When a protected member is inherited in public mode, it becomes
protected in the derived class too. i.e., it is ready for further
inheritance.
• When a protected member is inherited in private mode, it becomes
private in the derived class too. Also, the public members also
become private. i.e., it is not ready for further inheritance.
• The keywords private, public, protected may appear any no. of time
in the class declaration.
• Class can also be inherited in protected mode, both the public and
protected members of the base class become protected members of
the derived class.
Objects as Function Arguments
• Like a variable of any other type, objects can also be used as
arguments to the functions. There are two ways to do this:
1. A copy of the entire object is passed to the function. (Pass by
value)
2. Only the address of the object is passed to the function.(Pass by
Reference)
• Passing the address is more efficient as only the address is being
passed.
• An object can also be passed to the non-member functions, How
ever such functions can have access to the public member
functions only through the objects passed as argument to it.
• These functions cannot have access to the private member
functions.
Returning Objects
• The functions can also return the objects as the arguments.
– complex sum (complex c1, complex c2) {
complex c3;
c3.x = c1.x + c2.x;
return (c3);
}
• Const Member Functions: If a member function does not alter any
data in the class. Then we may declare it as const member. E.g.
void mul(int,int) const; //read only mode
double get_bal() const;
• It is generally appended to the function prototype, the compiler will
generate an error message, If such a functions try to alter the data
values.
Pointer to Members
• We can assign the address of the member of a class to a pointer.
• We can get the address by using the operator &.
• A class member pointer can be declared using the operator ::* with
the class name. e.g.
class A {
private:
int m;
public:
void show();
};
int A::* ip=&A :: m; \\ pointer to the member
• Here ip is a pointer to a member of class A and address of class
member of class A i.e., m is being assigned to ip.
• The statement int *ip=&m; \\ is wrong.
Pointer to Members
• Let us assume that we have a as an object of A declared in a member
function. We can access m using ip as:
cout<<a.*ip;
• Here is another example:
ap=&a;
cout<<ap->*ip;
cout<<ap->m;
• ->* is called dereferencing operator is used to access a member.
• The dereferencing operator .* is used when the object itself is used
with the member pointer. Here the *ip is used like member name.
• We can also have pointers to the member functions which can be
invoked using the dereferencing operators in the main().
(obj_name.* pointer-to-member function) ;
(pointer-to-object->*pointer-to-member function);
Local Classes
• Classes can be defined and used in a function or a block. Such
classes are called local classes. E.g.,
void test(int a) // function
{
::::::::::
class student //local class
{
::::::::::::::
};
:::::::::::::
student s1(a); //create student class object
::::::::::::::::::
}
Friend Functions
• The private members of a class can not be accessed from outside of
that class.
• In other words, a non-member function cannot have access to the
private data of a class.
• A friend functions is a special non-member function of a class that has
permission to access private data of a class.
• Friend function is not called with objects. Objects are usually passed
as arguments to the friend function.
• To make an outside function ‘friendly’, we have to simply declare this
function as a friend of the class.
• Friends can be of two types
– Friend function
– Friend class
Friend Functions
• The friend function definition does not use either the keyword friend
or the scope resolution operator :: .
• A function can be declared as a friend in any number of classes.
• A friend function has full access rights to the private members of the
class.
• Friend function is not in the scope of the class to which it has been
declared as friend.
• It can not be called using the object of that class.
• It can be invoked like a normal function.
• Usually, it has the objects as arguments.
Friend Function
#include <iostream> float mean(Sample s)
using namespace std; {
class Sample return float(s.a +s.b)/2.0;
}
{
int main()
int a; //private members {
int b; Sample x;
public: x.setvalue();
void setvalue() cout << “Mean value = “ <<
mean(x) << endl;
{
return 0;
a = 25; }
b = 40;
}
friend float mean(Sample s);
};
Friend Functions in Another Class
• Member function of one class can be a friend function of another
class. In such case they must be defined using scope resolution
operator.
class X
{
……………
int fun1(); // member function of X
……………
};
class Y
{
……………
friend int X :: fun1(); // fun1() of X is a friend of Y
};
Friend Function: XYZ Want Access of ABC Pr. Data
#include <iostream> friend void XYZ::compare(ABC obj);
using namespace std; };
class ABC; \\forward declaration void XYZ::compare (ABC obj) { //pass
Class XYZ { by value
{ if (x >= obj.a)
int x; //private data member cout << “XYZ is bigger”<<x;
public: else
void setvalue(int i) cout <<“ABC is
{ bigger:”<<obj.a<<endl;
x = i; }
} int main()
void compare(ABC obj); { {
XYZ xyz;
}; //member fun. of XYZ access ABC
ABC abc;
pr. data
xyz.setvalue(20);
class ABC { abc.setvalue(10);
int a; xyz.compare(abc); //free function
public: return 0;
void setvalue(int i) { a = i;} }
Friend Function: Compare ‘a’ and ‘x’ from two
different classes
#include <iostream> void setvalue(int i) { a = i;}
using namespace std; friend void max(XYZ, ABC);
class ABC; \\forward declaration };
Class XYZ { void max(XYZ m, ABC n) { //pass by
{ value
if (m.x >= n.a)
int x; //private data member
cout << m.x;
public:
else
void setvalue(int i)
cout <<n.a;
{
}
x = i; int main()
} {
friend void max(XYZ, ABC); { ABC abc;
abc.setvalue(10);
};
XYZ xyz;
class ABC { xyz.setvalue(20);
int a; max(xyz, abc); //free function
public: return 0;
}
Friend Class
• All the member functions of one class can be declared as the
friend functions of another class.
class Z
{
…………..
friend class X; // All the member functions of X are
// friend to Y
};
Friend Class: All Member Function of Class A Can
Access Private Data of Number Class
#include <iostream> void cube (Number x) {
using namespace std; cout<<“cube”<<x.n<<“is”<<(x.n*
class A; \\forward declaration x.n*x.n)<<endl;
Class Number { }
{ };
int n; //private data member int main()
public: {
void set(int value) Number p;
{ p.set(7);
A q;
n = value;
cout<<p.square()<<endl;
} q.cube(p);
int square() { return n*n;} return 0;
friend class A; { }
};
class A {
public: