13 Module 5 08 03 2024
13 Module 5 08 03 2024
FUNDAMENTALS
Dr. S. Vinila Jinny
Arrays within a class
• Arrays can be used as member variables in a class.
• Arrays can be declared as the members of a class.
• The arrays can be declared as private, public or
protected members of the class.
#include<iostream>
const int size=5;
class student
{
int roll_no;
example
int marks[size];
public:
void getdata ();
void student :: tot_marks() //calculating total marks
void tot_marks (); { Output:
}; int total=0;
void student :: getdata () for(int i=0; i<size; i++) Enter roll no: 101
{ total+ = marks[i]; Enter marks in subject 1: 67
cout<<"\nEnter roll no: "; cout<<"\n\nTotal marks "<<total; Enter marks in subject 2 : 54
Cin>>roll_no; }
Enter marks in subject 3 : 68
for(int i=0; i<size; i++) Enter marks in subject 4 : 72
{ void main()
Enter marks in subject 5 : 82
student stu;
cout<<"Enter marks in Total marks = 343
subject"<<(i+1)<<": "; stu.getdata() ;
cin>>marks[i] ; stu.tot_marks() ;
} getch();
}
C++ this Pointer
class class_name
{
friend data_type function_name(arguments/s);
//syntax of friend function.
};
#include <iostream>
Friend function
using namespace std;
class XYZ
{
private:
int num=100; int main()
char ch='Z';
{
public:
friend void disp(XYZ XYZ obj;
obj); disp(obj);
};
return 0;
void disp(XYZ obj){
cout<<obj.num<<endl;
}
cout<<obj.ch<<endl;
}
Characteristics of Friend Function in C++
• The function is not in the ‘scope’ of the class to
which it has been declared a friend.
• Friend functionality is not restricted to only one
class
• It cannot be invoked using the object as it is not in
the scope of that class.
• Friend functions have objects as arguments.
• It cannot access the member names directly and
has to use dot membership operator and use an
object name with the member name.
• We can declare it either in the ‘public’ or the
‘private’ part.
Member function as friend
class X
{
…..int fun1();
….
};
class y
{
….
friend int X::func1();
….
};
Friend Class
• A friend class can access both private and
protected members of the class in which it has
been declared as friend.
#include <iostream>
using namespace std;
class A Example
{
int main ()
int x=4;
friend class B; //friend class { Output:
value of x is:4
}; A a;
class B B b;
{
b. display (a);
public:
void display (A &a) return 0;
{ }
cout<<”value of x is:” <<a.x;
}
};
About Friend Class
• If class A is a friend of class B, then class B is not a
friend of class A.
• Also, if class A is a friend of class B, and then class
B is a friend of class C, class A is not a friend of
class C.
• If Base class is a friend of class X, subclass Derived
is not a friend of class X; and if class X is a friend of
class Base, class X is not a friend of subclass
Derived.