Lect 11
Lect 11
void get_x(A a)
{
cout<<a.x;
}
int main ()
{
A a;
get_x(a);
return 0;
}
Implementation of the friend functions: Friend Class
✓ Friend class is used when we need to access private and protected members of the class in which it has been declared as a friend.
✓ All functions in the friend class are friend functions of the other class required to be accessed.
✓ If class A is a friend of B, then B doesn’t become a friend of A automatically (Friendship is not mutual).
#include <iostream>
class class_name using namespace std;
{
friend class friend_class; class A
}; {
private:
class friend_class int x=4;
{ friend class B; //friend class
};
}; class B
{
public:
void get_x (A a)
{
cout<<a.x;
}
};
int main ()
{
A a;
B b;
b. get_x (a);
return 0;
}
Friend Function Example
#include <iostream>
using namespace std;
class Box
{
private:
int length=0;
public:
friend int printLength(Box);
};
int printLength(Box b)
{
b.length += 10;
return b.length;
}
int main()
{
Box b;
cout<<"Length of box: "<< printLength(b)<<endl;
return 0;
}
Function Overriding in C++.
✓ Redefinition of base class function in its derived class with the same signature i.e. return type and parameters.
✓ A function cannot be overridden multiple times as it is resolved at Run time.
✓ Overridden functions must have the same function signatures ( return type, name, parameters).
✓ Function Overriding occurs when the derived class and the base class functions are expected to perform differently.
✓ Can’t be executed without inheritance.
✓ Overridden functions are of different scopes.
#include <iostream>
using namespace std;
class employee
class manager : public employee
{
{
public:
public:
float salary;
manager(float sal): employee(sal)
public:
{
employee(float salary)
}
{
float get_bonus( float salary)
this->salary=salary;
{
}
return salary*0.2;
float get_bonus( float salary)
}
{
};
return salary*0.1;
}
};
Function Overriding in C++ (cont.).
int main()
{
float sal;
cout<<"Enter The salary"<<endl;
cin>>sal;
employee e(sal);
cout<<"Employee Bounus: "<< e.get_bonus(sal)<<endl;
manager m(sal);
cout<<"Manager Bounus: "<< m.get_bonus(sal)<<endl;
return 0;
}
Any Questions?????