CH4 2
CH4 2
Objects
LECTURE 2
Constant object and constant 2
member function
Constant object
Whose data member values cannot be changed
Can invoke constant member function only
Declared as,
const class_name object_name;
Constant object and constant 3
member function
Constant member function
Function in which data members remain constant
Uses ‘const’ as suffix in function declaration/definition
Return_type function_name(arg/s) const;
class alpha main()
{ int a; { 4
public: alpha s1 ;
alpha() : a(10) { } const alpha s2;
void display() s1.display();
{ //s2.display(); cannot invoke non-const func
a+=10; s1.show();
cout<<a<<endl; s2.show();
} }
void show()const
{
// a+=10; not permitted
cout<<a<<endl;
}
};
Static data member 5
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 declared as,
static data_type member;
Accessible within class and have lifetime of entire program.
It is initialized outside the class because its scope is not limited
to class but entire program.
Data_type class_name :: member =value;
OR
Data_type class_name :: member; // takes zero value by default
int item :: count ; //count defined
class item
int main( )
{
static int count; //count is static
{ 6
item a,b,c;
int number;
a.get_count( );
public: The output would be
b.get_count( ); count:0
void getdata()
c.get_count( ); count:0
{
count:0
number=count++; After reading data
a.getdata( ); count: 3
}
b.getdata( ); count:3
void getcount(void)
count:3
c.getdata( );
{
cout<<”count:”;
cout«"after reading data : "«endl;
cout<<count<<endl;
a.get_count( );
}
b.gel_count( );
};
c.get count( );
return(0);
}
Static member function 7
class alpha
{ public:
void showaddress()
{ cout<<this<<endl; }
};
main()
{ alpha s1 ;
s1.showaddress();
}
‘this’ pointer 10
main() main()
{ alpha *sp1; { int n;
sp1=new alpha; cin>>n;
sp1->showaddress(); alpha *sp[20];
for(int i=0;i<n;i++)
alpha *sp2=new alpha; {
sp2->showaddress(); sp[i]=new alpha;
sp[i]->showaddress();
} }
}
Friend functions 14
class B;
class A void A::show(B &x)
{ {
public: cout<<x.b;
void show(B&); }
};
main()
{
class B A m;
{ int b; B n;
public: m.show(n);
B():b(20){ } }
friend void A::show(B&);
};
Friend Class 18
A friend class can access all the private and protected data
members of the class to which it is friendly.
Member function of the friendly class becomes the friend
function to the class to which it is friendly.
Friend class is not mutual. That is, if the first class becomes
friend to second class, then it is not necessary that second
class is also friend to first class.
Friend Class 19
class B; void A::show(B &x)
class A {
cout<<a<<x.b;
{ int a;
}
public:
A():a(10){ }
main()
void show(B&);
{
}; A m;
B n;
m.show(n);
class B }
{ int b;
public: Note:1. friend class A can access
private member of B
B():b(20){} 2. Member function of class A
friend class A; becomes friend of B which can
access data of B.
};