Friendship and inheritance - C++ Tutorials
Friendship and inheritance - C++ Tutorials
Search: Go
Not logged in
C++
Information
Tutorials
Reference
Articles
Forum
Typical use cases of friend functions are operations that are conducted between two 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:
1 // friend class 16
2 #include <iostream> Edit
3 using namespace std; &
4 Run
5 class Square;
6
7 class Rectangle {
8 int width, height;
9 public:
10 int area ()
11 {return (width * height);}
12 void convert (Square a);
13 };
14
15 class Square {
16 friend class Rectangle;
17 private:
18 int side;
19 public:
20 Square (int a) : side(a) {}
21 };
22
23 void Rectangle::convert (Square a) {
24 width = a.side;
25 height = a.side;
26 }
27
28 int main () {
29 Rectangle rect;
https://www.cplusplus.com/doc/tutorial/inheritance/ 1/5
6/3/2021 Friendship and inheritance - C++ Tutorials
30 Square sqr (4);
31 rect.convert(sqr);
32 cout << rect.area();
33 return 0;
34 }
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 concretely, Rectangle accesses the member variable Square::side, which describes
the side of the square.
There is something else new in this example: at the beginning of the program, there is an empty declaration of class
Square. This is necessary 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 our example, Rectangle is considered a friend class by Square,
but Square is not considered a friend by Rectangle. Therefore, the member functions of Rectangle can access the
protected and private members of Square but not the other way around. Of course, Square could also be declared friend
of Rectangle, if needed, granting such an access.
Another property of friendships is that they are not transitive: The friend of a friend is not considered a friend unless
explicitly specified.
For example, let's imagine a series of classes to describe two kinds of polygons: rectangles and triangles. These two
polygons have certain common properties, such as the values needed to calculate their areas: they both can be
described simply with a height and a width (or base).
This could be represented in the world of classes with a class Polygon from which we would derive the two other ones:
Rectangle and Triangle:
The Polygon class would contain members that are common for both types of polygon. In our case: width and height.
And Rectangle and Triangle would be its derived classes, with specific features that are different from one type of
polygon to the other.
Classes that are derived from others inherit all the accessible members of the base class. That means that if a base
class includes a member A and we derive a class from it with another member called B, the derived class will contain
both member A and member B.
The inheritance relationship of two classes is declared in the derived class. Derived classes definitions use the following
syntax:
Where derived_class_name is the name of the derived class and base_class_name is the name of the class on which it is
based. The public access specifier may be replaced by any one of the other access specifiers (protected or private).
This access specifier limits the most accessible level for the members inherited from the base class: The members with
a more accessible level are inherited with this level instead, while the members with an equal or more restrictive access
level keep their restrictive level in the derived class.
1 // derived classes 20
2 #include <iostream> 10 Edit
3 using namespace std; &
4 Run
5 class Polygon {
6 protected:
7 int width, height;
8 public:
9 void set_values (int a, int b)
10 { width=a; height=b;}
11 };
12
13 class Rectangle: public Polygon {
14 public:
15 int area ()
16 { return width * height; }
17 };
18
19 class Triangle: public Polygon {
20 public:
21 int area ()
22 { return width * height / 2; }
23 };
24
25 int main () {
26 Rectangle rect;
27 Triangle trgl;
28 rect.set_values (4,5);
29 trgl.set_values (4,5);
30 cout << rect.area() << '\n';
https://www.cplusplus.com/doc/tutorial/inheritance/ 2/5
6/3/2021 Friendship and inheritance - C++ Tutorials
31 cout << trgl.area() << '\n';
32 return 0;
33 }
The objects of the classes Rectangle and Triangle each contain members inherited from Polygon. These are: width,
height and set_values.
The protected access specifier used in class Polygon is similar to private. Its only difference occurs in fact with
inheritance: When a class inherits another one, the members of the derived class can access the protected members
inherited from the base class, but not its private members.
By declaring width and height as protected instead of private, these members are also accessible from the derived
classes Rectangle and Triangle, instead of just from members of Polygon. If they were public, they could be accessed
just from anywhere.
We can summarize the different access types according to which functions can access them in the following way:
Where "not members" represents any access from outside the class, such as from main, from another class or from a
function.
In the example above, the members inherited by Rectangle and Triangle have the same access permissions as they
had in their base class Polygon:
This is because the inheritance relation has been declared using the public keyword on each of the derived classes:
This public keyword after the colon (:) denotes the most accessible level the members inherited from the class that
follows it (in this case Polygon) will have from the derived class (in this case Rectangle). Since public is the most
accessible level, by specifying this keyword the derived class will inherit all the members with the same levels they had
in the base class.
With protected, all public members of the base class are inherited as protected in the derived class. Conversely, if the
most restricting access level is specified (private), all the base class members are inherited as private.
For example, if daughter were a class derived from mother that we defined as:
This would set protected as the less restrictive access level for the members of Daughter that it inherited from mother.
That is, all members that were public in Mother would become protected in Daughter. Of course, this would not restrict
Daughter from declaring its own public members. That less restrictive access level is only set for the members inherited
from Mother.
If no access level is specified for the inheritance, the compiler assumes private for classes declared with keyword class
and public for those declared with struct.
Actually, most use cases of inheritance in C++ should use public inheritance. When other access levels are needed for
base classes, they can usually be better represented as member variables instead.
Even though access to the constructors and destructor of the base class is not inherited as such, they are automatically
called by the constructors and destructor of the derived class.
Unless otherwise specified, the constructors of a derived class calls the default constructor of its base classes (i.e., the
constructor taking no arguments). Calling a different constructor of a base class is possible, using the same syntax
used to initialize member variables in the initialization list:
For example:
https://www.cplusplus.com/doc/tutorial/inheritance/ 3/5
6/3/2021 Friendship and inheritance - C++ Tutorials
7 Mother ()
8 { cout << "Mother: no parameters\n"; }
9 Mother (int a)
10 { cout << "Mother: int parameter\n"; }
11 };
12
13 class Daughter : public Mother {
14 public:
15 Daughter (int a)
16 { cout << "Daughter: int parameter\n\n"; }
17 };
18
19 class Son : public Mother {
20 public:
21 Son (int a) : Mother (a)
22 { cout << "Son: int parameter\n\n"; }
23 };
24
25 int main () {
26 Daughter kelly(0);
27 Son bud(0);
28
29 return 0;
30 }
Notice the difference between which Mother's constructor is called when a new Daughter object is created and which
when it is a Son object. The difference is due to the different constructor declarations of Daughter and Son:
Multiple inheritance
A class may inherit from more than one class by simply specifying more base classes, separated by commas, in the list
of a class's base classes (i.e., after the colon). For example, if the program had a specific class to print on screen called
Output, and we wanted our classes Rectangle and Triangle to also inherit its members in addition to those of Polygon
we could write:
1 // multiple inheritance 20
2 #include <iostream> 10
3 using namespace std;
4
5 class Polygon {
6 protected:
7 int width, height;
8 public:
9 Polygon (int a, int b) : width(a), height(b) {}
10 };
11
12 class Output {
13 public:
14 static void print (int i);
15 };
16
17 void Output::print (int i) {
18 cout << i << '\n';
19 }
20
21 class Rectangle: public Polygon, public Output { Edit
22 public: &
23 Rectangle (int a, int b) : Polygon(a,b) {} Run
24 int area ()
25 { return width*height; }
26 };
27
28 class Triangle: public Polygon, public Output {
29 public:
30 Triangle (int a, int b) : Polygon(a,b) {}
31 int area ()
32 { return width*height/2; }
33 };
34
35 int main () {
36 Rectangle rect (4,5);
37 Triangle trgl (4,5);
38 rect.print (rect.area());
39 Triangle::print (trgl.area());
40 return 0;
41 }
Previous: Next:
Special members Polymorphism
Index
https://www.cplusplus.com/doc/tutorial/inheritance/ 4/5
6/3/2021 Friendship and inheritance - C++ Tutorials
https://www.cplusplus.com/doc/tutorial/inheritance/ 5/5