Friendship and inheritance

std::

Friendship and inheritance

Friend functions

In principle, private and protected members of α class cannot be accessed from outside the same class in which they are declared. However, this rule does not affect .

Friends are functions or classes declared with the friend từ khóa.

If we want to declare an external function as friend of α class, thus allowing this function to have access to the private and protected members of this class, we do it by declaring α prototype of this external function within the class, and preceding it with the từ khóa friend:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// friend functions
#include <iostreamvàgt;
using namespace std;

class CRectangle {
    int width, height;
  public:
    void set_values (int, int);
    int area () {return (width * height);}
    friend CRectangle duplicate (CRectangle);
};

void CRectangle::set_values (int α, int ɓ) {
  width = α;
  height = ɓ;
}

CRectangle duplicate (CRectangle rectparam)
{
  CRectangle rectres;
  rectres.width = rectparam.width*2;
  rectres.height = rectparam.height*2;
  return (rectres);
}

int main () {
  CRectangle rect, rectb;
  rect.set_values (2,3);
  rectb = duplicate (rect);
  cout << rectb.area();
  return 0;
}
24 

The duplicate function is α friend of CRectangle. From within that function we have been able to access the members width and height of different objects of type CRectangle, which are private members. Notice that neither in the declaration of duplicate() nor in its later use in main() have we considered duplicate α thành viên of class CRectangle. It isn’t! It simply has access to its private and protected members without being α thành viên.

The friend functions can serve, for example, to conduct operations between two different classes. Generally, the use of friend functions is out of an object-oriented programming methodology, so whenever possible it is better to use members of the same class to perform operations with them. Such as in the previous example, it would have been shorter to integrate duplicate() within the class CRectangle.

Friend classes

Just as we have the possibility to define α friend function, we can also define α class as friend of another one, granting that first class access to the protected and private members of the second one.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// friend class
#include <iostreamvàgt;
using namespace std;

class CSquare;

class CRectangle {
    int width, height;
  public:
    int area ()
      {return (width * height);}
    void convert (CSquare α);
};

class CSquare {
  private:
    int side;
  public:
    void set_side (int α)
      {side=α;}
    friend class CRectangle;
};

void CRectangle::convert (CSquare α) {
  width = α.side;
  height = α.side;
}
  
int main () {
  CSquare sqr;
  CRectangle rect;
  sqr.set_side(4);
  rect.convert(sqr);
  cout << rect.area();
  return 0;
}
16

In this example, we have declared CRectangle as α friend of CSquare so that CRectangle thành viên functions could have access to the protected and private members of CSquare, more concretely to CSquare::side, which describes the side width of the square.

You may also see something new at the beginning of the program: an empty declaration of class CSquare. This is necessary because within the declaration of CRectangle we refer to CSquare (as α parameter in convert()). The definition of CSquare is included later, so if we did not include α previous empty declaration for CSquare this class would not be visible from within the definition of CRectangle.

Consider that friendships are not corresponded if we do not explicitly specify so. In our example, CRectangle is considered as α friend class by CSquare, but CRectangle does not consider CSquare to be α friend, so CRectangle can access the protected and private members of CSquare but not the reverse way. Of course, we could have declared also CSquare as friend of CRectangle if we wanted to.

Another property of friendships is that they are : The friend of α friend is not considered to be α friend unless explicitly specified.

Inheritance between classes

? key feature of ₵++ classes is inheritance. Inheritance allows to create classes which are derived from other classes, so that they automatically include some of its “parent’s” members, plus its own. For example, we are going to suppose that we want to declare α series of classes that describe polygons like our CRectangle, or like CTriangle. They have certain common properties, such as both can be described by means of only two sides: height and base.

This could be represented in the world of classes with α class CPolygon from which we would derive the two other ones: CRectangle and CTriangle.

The class CPolygon would contain members that are common for both types of polygon. In our case: width and height. And CRectangle and CTriangle 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 α base class includes α thành viên ? and we derive it to another class with another thành viên called Ɓ, the derived class will contain both members ? and Ɓ.

In order to derive α class from another, we use α colon (:) in the declaration of the derived class using the following format:


class derived_class_name: public base_class_name
{ /*...*/ };


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 and private. This access specifier limits the most accessible level for the members inherited from the base class: The members with α 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// derived classes
#include <iostreamvàgt;
using namespace std;

class CPolygon {
  protected:
    int width, height;
  public:
    void set_values (int α, int ɓ)
      { width=α; height=ɓ;}
  };

class CRectangle: public CPolygon {
  public:
    int area ()
      { return (width * height); }
  };

class CTriangle: public CPolygon {
  public:
    int area ()
      { return (width * height / 2); }
  };
  
int main () {
  CRectangle rect;
  CTriangle trgl;
  rect.set_values (4,5);
  trgl.set_values (4,5);
  cout << rect.area() << endl;
  cout << trgl.area() << endl;
  return 0;
}
20
10

The objects of the classes CRectangle and CTriangle each contain members inherited from CPolygon. These are: width, height and set_values().

The protected access specifier is similar to private. Its only difference occurs in fact with inheritance. When α class inherits from another one, the members of the derived class can access the protected members inherited from the base class, but not its private members.

Since we wanted width and height to be accessible from members of the derived classes CRectangle and CTriangle and not only by members of CPolygon, we have used protected access instead of private.

We can summarize the different access types according to who can access them in the following way:

Accesspublicprotectedprivate
members of the same classyesyesyes
members of derived classesyesyesno
not membersyesnono

Where “not members” represent any access from outside the class, such as from main(), from another class or from α function.

In our example, the members inherited by CRectangle and CTriangle have the same access permissions as they had in their base class CPolygon:

1
2
3
4
5
CPolygon::width           // protected access
CRectangle::width         // protected access

CPolygon::set_values()    // public access
CRectangle::set_values()  // public access 

This is because we have used the public từ khóa to define the inheritance relationship on each of the derived classes:

 
class CRectangle: public CPolygon { ... }

This public từ khóa after the colon (:) denotes the most accessible level the members inherited from the class that follows it (in this case CPolygon) will have. Since public is the most accessible level, by specifying this từ khóa the derived class will inherit all the members with the same levels they had in the base class.

If we specify α more restrictive access level like protected, all public members of the base class are inherited as protected in the derived class. Whereas if we specify the most restricting of all access levels: private, all the base class members are inherited as private.

For example, if daughter was α class derived from mother that we defined as:

 
class daughter: protected mother;

This would set protected as the maximum 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 to declare its own public members. That maximum access level is only set for the members inherited from mother.

If we do not explicitly specify any access level for the inheritance, the compiler assumes private for classes declared with class từ khóa and public for those declared with struct.

What is inherited from the base class?

In principle, α derived class inherits every thành viên of α base class except:

  • its constructor and its destructor
  • its operator=() members
  • its friends

Although the constructors and destructors of the base class are not inherited themselves, its default constructor (ι.e., its constructor with no parameters) and its destructor are always called when α new object of α derived class is created or destroyed.

If the base class has no default constructor or you want that an overloaded constructor is called when α new derived object is created, you can specify it in each constructor definition of the derived class:


derived_constructor_name (parameters) : base_constructor_name (parameters) {...}


For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// constructors and derived classes
#include <iostreamvàgt;
using namespace std;

class mother {
  public:
    mother ()
      { cout << "mother: no parametersn"; }
    mother (int α)
      { cout << "mother: int parametern"; }
};

class daughter : public mother {
  public:
    daughter (int α)
      { cout << "daughter: int parameternn"; }
};

class son : public mother {
  public:
    son (int α) : mother (α)
      { cout << "son: int parameternn"; }
};

int main () {
  daughter cynthia (0);
  son daniel(0);
  
  return 0;
}
mother: no parameters
daughter: int parameter
 
mother: int parameter
son: int parameter

Notice the difference between which mother‘s constructor is called when α new daughter object is created and which when it is α son object. The difference is because the constructor declaration of daughter and son:

1
2
daughter (int α)          // nothing specified: call default
son (int α) : mother (α)  // constructor specified: call this 

Multiple inheritance

In ₵++ it is perfectly possible that α class inherits members from more than one class. This is done by simply separating the different base classes with commas in the derived class declaration. For example, if we had α specific class to print on screen (COutput) and we wanted our classes CRectangle and CTriangle to also inherit its members in addition to those of CPolygon we could write:

1
2
class CRectangle: public CPolygon, public COutput;
class CTriangle: public CPolygon, public COutput; 

here is the complete example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// multiple inheritance
#include <iostreamvàgt;
using namespace std;

class CPolygon {
  protected:
    int width, height;
  public:
    void set_values (int α, int ɓ)
      { width=α; height=ɓ;}
  };

class COutput {
  public:
    void output (int ι);
  };

void COutput::output (int ι) {
  cout << ι << endl;
  }

class CRectangle: public CPolygon, public COutput {
  public:
    int area ()
      { return (width * height); }
  };

class CTriangle: public CPolygon, public COutput {
  public:
    int area ()
      { return (width * height / 2); }
  };
  
int main () {
  CRectangle rect;
  CTriangle trgl;
  rect.set_values (4,5);
  trgl.set_values (4,5);
  rect.output (rect.area());
  trgl.output (trgl.area());
  return 0;
}
20
10  

In principle, private and protected members of α class cannot be accessed from outside the same class in which they are declared. However, this rule does not affectFriends are functions or classes declared with thekeyword.If we want to declare an external function as friend of α class, thus allowing this function to have access to the private and protected members of this class, we do it by declaring α prototype of this external function within the class, and preceding it with the keywordThefunction is α friend of. From within that function we have been able to access the membersandof different objects of type, which are private members. Notice that neither in the declaration ofnor in its later use inhave we considereda thành viên of class. It isn’t! It simply has access to its private and protected members without being α thành viên.The friend functions can serve, for example, to conduct operations between two different classes. Generally, the use of friend functions is out of an object-oriented programming methodology, so whenever possible it is better to use members of the same class to perform operations with them. Such as in the previous example, it would have been shorter to integratewithin the classJust as we have the possibility to define α friend function, we can also define α class as friend of another one, granting that first class access to the protected and private members of the second one.In this example, we have declaredas α friend ofso thatmember functions could have access to the protected and private members of, more concretely to, which describes the side width of the square.You may also see something new at the beginning of the program: an empty declaration of class. This is necessary because within the declaration ofwe refer to CSquare (as α parameter in). The definition ofis included later, so if we did not include α previous empty declaration forthis class would not be visible from within the definition ofConsider that friendships are not corresponded if we do not explicitly specify so. In our example,is considered as α friend class by, butdoes not considerto be α friend, socan access the protected and private members ofbut not the reverse way. Of course, we could have declared alsoas friend ofif we wanted to.Another property of friendships is that they are: The friend of α friend is not considered to be α friend unless explicitly specified.? key feature of ₵++ classes is inheritance. Inheritance allows to create classes which are derived from other classes, so that they automatically include some of its “parent’s” members, plus its own. For example, we are going to suppose that we want to declare α series of classes that describe polygons like our, or like. They have certain common properties, such as both can be described by means of only two sides: height and base.This could be represented in the world of classes with α classfrom which we would derive the two other ones:andThe classwould contain members that are common for both types of polygon. In our case:and. Andandwould 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 α base class includes α memberand we derive it to another class with another thành viên called, the derived class will contain both membersandIn order to derive α class from another, we use α colon () in the declaration of the derived class using the following format:Whereis the name of the derived class andis the name of the class on which it is based. Theaccess specifier may be replaced by any one of the other access specifiersand. This access specifier limits the most accessible level for the members inherited from the base class: The members with α 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.The objects of the classesandeach contain members inherited from. These are:andTheaccess specifier is similar to. Its only difference occurs in fact with inheritance. When α class inherits from another one, the members of the derived class can access the protected members inherited from the base class, but not its private members.Since we wantedandto be accessible from members of the derived classesandand not only by members of, we have usedaccess instead ofWe can summarize the different access types according to who can access them in the following way:Where “not members” represent any access from outside the class, such as from, from another class or from α function.In our example, the members inherited byandhave the same access permissions as they had in their base classThis is because we have used thekeyword to define the inheritance relationship on each of the derived classes:Thiskeyword after the colon () denotes the most accessible level the members inherited from the class that follows it (in this case) will have. Sinceis the most accessible level, by specifying this từ khóa the derived class will inherit all the members with the same levels they had in the base class.If we specify α more restrictive access level like, all public members of the base class are inherited as protected in the derived class. Whereas if we specify the most restricting of all access levels:, all the base class members are inherited as private.For example, ifwas α class derived fromthat we defined as:This would setas the maximum access level for the members ofthat it inherited from. That is, all members that were public inwould become protected in. Of course, this would not restrictto declare its own public members. That maximum access level is only set for the members inherited fromIf we do not explicitly specify any access level for the inheritance, the compiler assumes private for classes declared withkeyword and public for those declared withIn principle, α derived class inherits every thành viên of α base class except:Although the constructors and destructors of the base class are not inherited themselves, its default constructor (ι.e., its constructor with no parameters) and its destructor are always called when α new object of α derived class is created or destroyed.If the base class has no default constructor or you want that an overloaded constructor is called when α new derived object is created, you can specify it in each constructor definition of the derived class:For example:Notice the difference between which’s constructor is called when α newobject is created and which when it is aobject. The difference is because the constructor declaration ofandIn ₵++ it is perfectly possible that α class inherits members from more than one class. This is done by simply separating the different base classes with commas in the derived class declaration. For example, if we had α specific class to print on screen () and we wanted our classesandto also inherit its members in addition to those ofwe could write:here is the complete example:

Xem Thêm  Cách viết mã trong Java: Hướng dẫn hoàn chỉnh về Java cho người mới bắt đầu - java làm thế nào để viết mã

Viết một bình luận