C++ Friend Function
C++ Friend Function
• s2.getdata();
• s2.putdata();
• Student s3;
• s3.getdata();
• s3.putdata();
• cout << "Total objects created = " << Student::objectCount << endl;
• return 0;
• }
Output:
Enter roll number: 1
Enter name: Mark
Enter marks: 78
Roll Number = 1
Name = Mark
Marks = 78
Enter roll number: 2
Enter name: Nancy
Enter marks: 55
Roll Number = 2
Name = Nancy
Marks = 55
Enter roll number: 3
Enter name: Susan
Enter marks: 90
Roll Number = 3
Name = Susan
Marks = 90
Total objects created = 3
Program Explanation
• The static variable count is initialized to 0
when the objects are created.
• The count is incremented whenever the data
is read into an object.
• Since the data is read into objects three times
the variable count is incremented 3 times.
• Because there is only one copy of the
objectCount variable shared by all the three
objects, all the 3 output statement cause the
value 3 to be displayed.
Diagram
Static Member Function
• A static member function is a member
function of a class that is defined with the
static keyword.
class A
{
static void sayHello()
{
cout<<"Hello world!"
}
};
Syntax
class_name::function_name (parameter);
• public:
• student()
• {
• cout << "Enter the RollNo:";
• cin >> rno;
• cout << "Enter the Name:";
• cin >> name;
• cout << "Enter the Fee:";
• cin >> fee;
• }
• void display()
• {
• cout << endl << rno << "\t" << name << "\t" << fee;
• }
• };
• int main()
• {
• student s; // constructor gets called automatically when we create the object of the class
• s.display();
• return 0;
• }
Example: Outside the Class
• #include <iostream>
• using namespace std;
• class student {
• int rno;
• char name[50];
• double fee;
• public:
• student();
• void display();
• };
• student::student()
• {
• cout << "Enter the RollNo:";
• cin >> rno;