0% found this document useful (0 votes)
315 views

C++ Friend Function

C++ friend functions allow non-member functions to access private and protected members of a class. A friend function is declared inside the class using the friend keyword. It can access private and protected members of its friend class but is defined outside the class like a regular function. Friend functions are useful when classes are tightly coupled and require accessing each other's non-public members.

Uploaded by

SGamer YT
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
315 views

C++ Friend Function

C++ friend functions allow non-member functions to access private and protected members of a class. A friend function is declared inside the class using the friend keyword. It can access private and protected members of its friend class but is defined outside the class like a regular function. Friend functions are useful when classes are tightly coupled and require accessing each other's non-public members.

Uploaded by

SGamer YT
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

C++ Friend function

• If a function is defined as a friend function in


C++, then the protected and private data of a
class can be accessed using the function.
• By using the keyword friend compiler knows
the given function is a friend function.
• For accessing the data, the declaration of a
friend function should be done inside the
body of a class starting with the keyword
friend.
Example: Without using Friend Function
Declaration of friend function in C++
class class_name
{
friend data_type function_name(argument/s)
// syntax of friend function.
};
1. In the above declaration, the friend function is preceded by the
keyword friend.
2. The function can be defined anywhere in the program like a
normal C++ function.
3. The function definition does not use either the keyword friend
or scope resolution operator.
Example: Using Friend Function
• #include <iostream>
• using namespace std;
• class Box
• {
• private:
• int length;
• public:
• Box(): length(0) { }
• friend int printLength(Box); //friend function
• };
• int printLength(Box b)
• {
• b.length += 10;
• return b.length;
• }
• int main()
• {
• Box b;
• cout<<"Length of box: "<< printLength(b)<<endl;
• return 0;
• }
Characteristics of a Friend function:
• The function is not in the scope of the class to
which it has been declared as a friend.
• It cannot be called using the object as it is not in
the scope of that class.
• It can be invoked like a normal function without
using the object.
• It cannot access the member names directly and
has to use an object name and dot membership
operator with the member name.
• It can be declared either in the private or the
public part.
Advantages of Friend Function in C++
• The friend function allows the programmer to
generate more efficient codes.
• It allows the sharing of private class information
by a non-member function.
• It accesses the non-public members of a class
easily.
• It is widely used in cases when two or more
classes contain the interrelated members relative
to other parts of the program.
• It allows additional functionality that is not used
by the class commonly.
Static data members in C++
• Static data members are class members that are
declared using static keywords.
• Syntax
static data_type data_member_name;
• A static member has certain special characteristics.
• These are:
1. 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.
2. It is initialized before any object of this class is
being created, even before main starts.
3. It is visible only within the class, but its lifetime is
the entire program
Code Snippet
class A class A
{ {
static int x; //Declaration
}; static int x;
};
//Definition
int A::x=0;
Example:
• #include <iostream>
• #include<string.h>
• using namespace std;
• class Student
• {
• private:
• int rollNo;
• char name[10];
• int marks;
• public:
• static int objectCount;
• Student()
• {
• objectCount++;
• }
• void getdata()
• {
• cout << "Enter roll number: "<<endl;
• cin >> rollNo;
• cout << "Enter name: "<<endl;
• cin >> name;
• cout << "Enter marks: "<<endl;
• cin >> marks;
• }
• void putdata()
• {
• cout<<"Roll Number = "<< rollNo <<endl;
• cout<<"Name = "<< name <<endl;
• cout<<"Marks = "<< marks <<endl;
• cout<<endl;
• }
• };
• int Student::objectCount = 0;
• int main(void)
• {
• Student s1;
• s1.getdata();
• s1.putdata();
• Student s2;

• 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);

• Here, the class_name is the name of the class.


• function_name: The function name is the
name of the static member function.
• parameter: It defines the name of the pass
arguments to the static member function.
Static Member Function
• The sayHello() function above is a static member
function of class A.
• Static data members of a class can only be
defined within static member functions and a
static member function can call other static
member functions of the class.
• A static member function cannot define a non-
static data member and cannot call a non-static
member function.
• A static member function need not be
instantiated and can be called without creating
any object of the class by using the scope
resolution operator(::).
Example
• #include <iostream>
• using namespace std;
• class Note
{
• static int num; // declare a static data member
• public:
• static int func () // create static member function
• {
• return num;
• }
};
// initialize the static data member using the class name and the scope resolution
operator
• int Note :: num = 5;
• int main ()
• {
// access static member function using the class name and the scope resolution
• cout << " The value of the num is: " << Note:: func () << endl;
• return 0;
• }
Function Overloading in C++
• Function overloading is a feature of object-
oriented programming where two or more
functions can have the same name but
different parameters.
• When a function name is overloaded with
different jobs it is called Function Overloading.
• In Function Overloading “Function” name
should be the same and the arguments should
be different.
• Function overloading can be considered as an
example of a polymorphism feature in C++.
Example:
• #include <iostream>
• using namespace std;
• class Cal
• {
• public:
• static int add(int a,int b)
• {
• return a + b;
• }
• static int add(int a, int b, int c)
• {
• return a + b + c;
• }
• };
• int main(void)
• {
• Cal C; // class object declaration.
• cout<<C.add(10, 20)<<endl;
• cout<<C.add(12, 20, 23);
• return 0;
• }
Passing objects as arguments
• In C++ programming, we can pass objects to a
function in a similar manner as passing regular
arguments.
• To pass an object as an argument, the object
name should be used as the argument while
calling the function the same way to do it for
other variables.
Syntax:
function_name(object_name);
• #include <iostream> Example
• using namespace std;
• class Student
• {
• public:
• double marks;
• Student(double m)
• {
• marks = m;
• }
• };
• void calculateAverage(Student s1, Student s2)
• {
• double average = (s1.marks + s2.marks) / 2;
• cout << "Average Marks = " << average << endl;
• }
• int main()
• {
• Student student1(88.0), student2(56.0);
• calculateAverage(student1, student2);
• return 0;
• }
Explanation
C++ Return Object from a Function
• #include <iostream>
• using namespace std;
• class Student
• {
• public:
• double marks1, marks2;
• };
• Student createStudent()
• {
• Student student;
• student.marks1 = 96.5;
• student.marks2 = 75.0;
• cout << "Marks 1 = " << student.marks1 << endl;
• cout << "Marks 2 = " << student.marks2 << endl;
• return student;
• }
• int main()
• {
• Student student1;
• student1 = createStudent();
• return 0;
• }
Explanation
Unit – II
Constructor in C++
• In C++, constructor is a special method which is
invoked automatically at the time of object
creation.
• It is used to initialize the data members of new
object generally.
• The constructor in C++ has the same name as
class or structure.
• There can be two types of constructors in C++.
1. Default constructor
2. Parameterized constructor
Syntax:
• The syntax for defining the constructor within the
class:
<class-name> (list-of-parameters)
{
// constructor definition
}
• The syntax for defining the constructor outside
the class:
<class-name>: :<class-name> (list-of-parameters)
{
// constructor definition
}

Example: Inside the Class
#include <iostream>
• using namespace std;
• class student {
• int rno;
• char name[10];
• double fee;

• 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;

• cout << "Enter the Name:";


• cin >> name;

• cout << "Enter the Fee:";


• cin >> fee;
• }
• void student::display()
• {
• cout << endl << rno << "\t" << name << "\t" << fee;
• }
• int main()
• {
• student s;
• s.display();
• return 0;
• }
C++ Default Constructor

• A constructor which has no argument is


known as default constructor.
• It is invoked at the time of creating object.
Example:
• #include <iostream>
• using namespace std;
• class Employee
• {
• public:
• Employee()
• {
• cout<<"Default Constructor Invoked"<<endl;
• }
• };
• int main(void)
• {
• Employee e1; //creating an object of Employee
• Employee e2;
• return 0;
• }
C++ Parameterized Constructor

• A constructor which has parameters is called


parameterized constructor.
• It is used to provide different values to distinct
objects.
• #include <iostream> Example
• using namespace std;
• class Employee
• {
• public:
• int id; //data member (also instance variable)
• string name; //data member(also instance variable)
• float salary;
• Employee(int i, string n, float s)
• {
• id = i;
• name = n;
• salary = s;
• }
• void display()
• {
• cout<<id<<" "<<name<<" "<<salary<<endl;
• }
• };
• int main(void)
• {
• Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee
• Employee e2=Employee(102, "Nakul", 59000);
• e1.display();
• e2.display();
• return 0;
• }

You might also like