Friend Function
Friend Function
#include <iostream>
3. class Employee {
4. public:
7. float salary;
9. {
13. }
15. {
17. }
18. };
22. e1.display();
23. e2.display();
24. return 0;
25. }
Output:
Friend Function
Friend function is a function which is not the member of the class instead of that it can access private
and protected members of class.
Syntax
Class a
Int a,b;
Public:
Void input()
Cout<<”enter values”;
Cin>>a>>b;
Int c;
C=ob.a+ob.b;
Cout<<”sum is”<<c;
Int main()
A kk;
kk.input();
add(kk);
return 0;
C++ Constructor
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.
o Default constructor
o Parameterized constructor
A constructor which has no argument is known as default constructor. It is invoked at the time of
creating object.
1. #include <iostream>
3. class Employee
4. {
5. public:
6. Employee()
7. {
8. cout<<"Default Constructor Invoked"<<endl;
9. }
10. };
12. {
15. return 0;
16. }
Output:
A constructor which has parameters is called parameterized constructor. It is used to provide different
values to distinct objects.
#include <iostream>
class Employee {
public:
float salary;
id = i;
name = n;
salary = s;
void display()
};
int main(void) {
e1.display();
e2.display();
return 0;
Output:
C++ Destructor
A destructor works opposite to constructor; it destructs the objects of classes. It can be defined only
once in a class. Like constructors, it is invoked automatically.
A destructor is defined like constructor. It must have same name as class. But it is prefixed with a tilde
sign (~).
Let's see an example of constructor and destructor in C++ which is called automatically.
1. #include <iostream>
2. using namespace std;
3. class Employee
4. {
5. public:
6. Employee()
7. {
8. cout<<"Constructor Invoked"<<endl;
9. }
10. ~Employee()
11. {
13. }
14. };
16. {
19. return 0;
20. }
Output:
Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked