Login

Username:

Password: 

Join us Now |  Forgot Password? | Forgot UserName?

C++

Learn step by step



Friendship and inheritance

Friend functions

In principle, private and protected members of a class cannot be accessed from outside the same class in which they are declared. However, this rule does not apply to "friends".

Friends are the functions or classes declared with the friend keyword.

A non-member function can access the private and protected members of a class if it is declared a friend of that class. This is done by including a declaration of this external function within class, and preceding it with the keyword friend:


// friend functions
#include <iostream>
using namespace std;

class Rectangle {
int width, height;
public:
Rectangle() {}
Rectangle (int x, int y) : width(x), height(y) {}
int area() {return width * height;}
friend Rectangle duplicate (const Rectangle&);
};

Rectangle duplicate (const Rectangle& param)
{
Rectangle res;
res.width = param.width*2;
res.height = param.height*2;
return res;
}

int main () {
Rectangle foo;
Rectangle bar (2,3);
foo = duplicate (bar);
cout << foo.area() << '\n';
return 0;
}

Output

24

Duplicate function is a friend of class Rectangle. So, function duplicate is able to access the members width and height (which are private) of different objects of type Rectangle. Note that though that neither in the declaration of duplicate nor in its later use in main, the member function duplicate is considered a member of class Rectangle. It is not! It simply has access to private and protected members of class without being a member.

Typical use cases of the friend functions are operations that are conducted between 2 different classes accessing private or protected members of both.

Friend classes

Similar to friend functions, a friend class is a class whose members have access to the private or protected members of another class:


// friend class
#include <iostream>
using namespace std;

class Square;

class Rectangle {
int width, height;
public:
int area ()
{return (width * height);}
void convert (Square a);
};

class Square {
friend class Rectangle;
private:
int side;
public:
Square (int a) : side(a) {}
};

void Rectangle::convert (Square a) {
width = a.side;
height = a.side;
}

int main () {
Rectangle rect;
Square sqr (4);
rect.convert(sqr);
cout << rect.area();
return 0;
}

Output

16

In this example, class Rectangle is a friend of class Square allowing Rectangle's member functions to access private and protected members of Square. More accurately, Rectangle accesses the member variable Square::side, which describes side of the square.

There is something else new in this example: at the beginning of program, there is an empty declaration of class Square. This is essential because class Rectangle uses Square (as a parameter in member convert), and Square uses Rectangle (declaring it a friend).

Friendships are never corresponded unless specified: In the example, Rectangle is considered a friend class by Square, however Square is not considered a friend by Rectangle. So, the member functions of Rectangle can access the protected and private members of Square but not the other way around. Of course, the Square could also be declared as a friend of Rectangle, if needed, then granting such an access.

Another property of friendship is that they are not transitive: Friend of a friend is not considered a friend unless explicitly specified.

C++ Inheritance

Inheritance is one of the key feature of object-oriented programming including C++ which allows user to create a new class(derived class) from a existing class(base class). Derived class inherits all feature from a base class and it can have additional features of its own.

Fig 1.

Concept of Inheritance in OOP

Suppose, we want to calculate either area, perimeter or diagonal length of rectangle by taking data(length and breadth) from user. We can create three different objects( Area, Perimeter & Diagonal) and asks user to enter length and breadth in each object and calculate corresponding data. But, better approach would be to create a additional object Rectangle to store value of length and breadth from user and derive objects Area, Perimeter & Diagonal from Rectangle base class. It is because, all 3 objects Area, Perimeter and diagonal are related to the object Rectangle and we don't need to ask user the input data from these three derived objects as this feature is included in base class.

Fig 2.

Implementation of Inheritance in C++ Programming
class Rectangle
{
... .. ...
};

class Area : public Rectangle
{
... .. ...
};

class Perimeter : public Rectangle
{
.... .. ...
};

In above example, class Rectangle is a base class and classes Area and Perimeter are the derived from Rectangle. Derived class appears with the declaration of class followed by a colon, keyword public and the name of base class from which it is derived.

Since, Area & Perimeter are derived from Rectangle, all data member and member function of base class Rectangle can be accessible from derived class.

Note that keywords private and protected can be used in place of public while defining derived class(will be discussed later).

Example calculates area and perimeter a rectangle using the concept of inheritance.



/* C++ Program to calculate the area and perimeter of rectangles using concept of inheritance. */

#include <iostream>
using namespace std;
class Rectangle
{
protected:
float length, breadth;
public:
Rectangle(): length(0.0), breadth(0.0)
{
cout<<"Enter length: ";
cin>>length;
cout<<"Enter breadth: ";
cin>>breadth;
}

};

/* Area class is derived from base class Rectangle. */
class Area : public Rectangle
{
public:
float calc()
{
return length*breadth;
}

};

/* Perimeter class is derived from base class Rectangle. */
class Perimeter : public Rectangle
{
public:
float calc()
{
return 2*(length+breadth);
}
};

int main()
{
cout<<"Enter data for first rectangle to find area.\n";
Area a;
cout<<"Area = "<<a.calc()<<" square meter\n\n";

cout<<"Enter data for second rectangle to find perimeter.\n";
Perimeter p;
cout<<"\nPerimeter = "<<p.calc()<<" meter";
return 0;
}

Output

Enter data for first rectangle to find area.
Enter length: 5
Enter breadth: 4
Area = 20 square meter

Enter data for second rectangle to find perimeter.
Enter length: 3
Enter breadth: 2
Area = 10 meter

Explanation of Program
In this program, classes Area and Perimeter are derived from class Rectangle. Thus, object of derived class can access the public members of Rectangle. In this program, when the objects of class Area and Perimeter are created, constructor in the base class is automatically called. If there was public member function in the base class then, those functions would have been also accessible for objects a and p.

Keyword protected

In this program, length and breadth in the base class are protected data members of that class. These data members are accessible from the derived class but, not accessible from outside of it. This maintains feature of data hiding in C++. If we defined length and breadth as private members then, those 2 data are not accessible to derived class and if defined as public members, it can be accessible from both the derived class and from main( ) function.

Accessibilityprivateprotectedpublic
Accessible from own class ?yesyesyes
Accessible from derived class ?noyesyes
Accessible outside derived class ?nonoyes
Public, Protected and Private Inheritance in C++ Programming

We can declare a derived class from a base class with different access control, i.e., public, protected or private inheritance.

class base
{
.... ... ....
};

class derived : access_specifier base
{
.... ... ....
};

/* Note: Either keyword public, protected or private is used in place of access_specifier. */
Important points to remember.

  • Protected and public members(data & function) of a base class are accessible from a derived class(for all 3: public, protected and private inheritance).
  • Objects of the derived class with private and protected inheritance cannot access any data member of a base class.
  • Objects of the derived class with public inheritance can access only public member of a base class.

Fig 3.

Summary
Accessibility in Public Inheritance

Accessibility privateprotectedpublic
Accessible from own class?yesyesyes
Accessible from derived class?noyesyes
Accessible outside derived class?nonoyes


Accessibility in Protected Inheritance

Accessibilityprivateprotectedpublic
Accessible from own class?yesyesyes
Accessible from derived class?noyesyes
Accessible outside derived class?nonono


Accessibility in Private Inheritance

Accessibilityprivateprotectedpublic
Accessible from own class?yesyesyes
Accessible from derived class?noyesyes
Accessible outside derived class?nonono
C++ Function Overriding

If base class and derived class have member functions with same name and arguments. If we create an object of derived class and write code to access that member function then, member function in derived class is only invoked, i.e., member function of derived class overrides the member function of base class. This feature in C++ programming is known as function overriding.

Accessing the Overridden Function in Base Class From Derived Class

To access the overridden function of base class from derived class, scope resolution operator ::. For example: If we want to access get_data() function of base class from derived class in above example then, following statement is used in derived class.

A::get_data; // Calling function get_data() of class A.

It is because, if name of class is not specified, the compiler thinks get_data() function is calling itself.



Related Videos