[C++] Default member function of a class—-const member function (super detailed analysis)

Table of Contents

I. Introduction

2. const member function

const modified member function of the class

Question 1

Question 2

Frequently asked interview questions for const member functions (key points!!)

Address-taking and const address-taking operator overloading

3. Encouragement


1. Foreword

In the class we studied earlier, we will define member variables and member functions. These functions we define ourselves are ordinary member functions. , but what if there is nothing in the class we define? Is it true that there is nothing inside? as follows:

class Date {};

If there are no members in a class, it is called empty class for short. Is there nothing in the empty class? No, any class will automatically generate 6 default member functions if we don’t write them.

[Concept of default member function]: If the user does not implement it explicitly, the member function generated by the compiler is called the default member function.

?The last blog has explained in detail the use of constructors & destructors, copy constructors and assignment operator overloading, so this blog will continue to explain the const member function issue in depth ?

2. const member function

const modified member function of class

[Concept]: The “member function” modified by const is called a const member function. The const modified class member function actually modifies the implicit of the member function. this pointer, indicates that no member of the class can be modified in this member function

Question 1

Suppose I have a date class now and the following Func function is called:

class Date
{
public:
\t//Constructor
Date(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
void Printf()
{
cout << _year << "year" << _month << "month" << _day << "day" << endl;
}
private:
int _year;
int _month;
int _day;
};

void Func(const Date & d)
{
d.Printf();
}

int main()
{
Date d1(2023, 11, 1);
d1.Printf();
Date d2(2023, 11, 2);
Func(d2);
return 0;
}

An error occurred at this time. Why is this?

Obviously, there is an error when Func function d calls Print(), but there is no error when d1 calls Print(). Why?

This involvespermission issues. Let’s first write out the implicit this pointer during the actual call:
If you don’t know about this pointer, you can read this blog: Detailed explanation of this pointer


The const in the Print() function modifies this itself. This cannot be modified, but this can be initialized. Then we need to figure out what the types of &d1 and &d are:

  • &d1:Date*
  • &d:const Date*
  1. There is no problem with passing Date* to Date* const. They are both readable and modifiable, so there will be no error when d1 calls Print().
  2. The content pointed to by const Date* cannot be modified, but an error occurs when it is passed to Date*, because Date* can be modified, and passing it here will cause permission amplification. So of course d calls the Print() function and reports an error.

Solution:
Add const to protect the content pointed to by this, that is, add const in front of Date*:

void Print(const Date* const this)
{
cout << _year << "year" << _month << "month" << _day << "day" << endl;
}

But you can’t add const here, because this pointer is implicit, and you can’t write const explicitly. Therefore, in order to solve this problem, C++ allows adding const after the function to achieve the just effect:

void Print() const// The compiler defaults to: void Print(const Date* const this)
{
cout << _year << "-" << _month << "-" << _day << endl;
}

At this time, if I pass const Date* to const Date*, the permissions will remain unchanged, so there will be no error. Similarly, if I pass Date* to const Date*, there will be no problem if the permissions are reduced. Because permissions cannot be enlarged, they can only be reduced or unchanged.

Correct code:

class Date
{
public:
\t//Constructor
Date(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
void Printf() const // void Printf(Date* const this)
{
cout << _year << "year" << _month << "month" << _day << "day" << endl;
}
private:
int _year;
int _month;
int _day;
};

void Func(const Date & d)
{
d.Printf(); // d.Printf( & amp;d);
}

int main()
{
Date d1(2023, 11, 1);
d1.Printf(); // d1.Printf( & amp;d);
Date d2(2023, 11, 2);
cout << endl;
Func(d2);
return 0;
}

Question 2

Suppose we encounter the following custom type comparison situation:

class Date
{
public:
\t//Constructor
Date(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
bool operator<(const Date & d)
{
if (_year < d._year ||
_year == d._year & amp; & amp; _month < d._month ||
_year == d._year & amp; & amp; _month == d._month & amp; & amp; _day < d._day)
{
return true;
}
else
{
return false;
}
}
private:
int _year;
int _month;
int _day;
};

int main()
{
Date d1(2023, 11, 1);
const Date d2(2023, 11, 2);
cout << endl;
d1 < d2;
d2 < d1;
return 0;
}

An error occurred at this time. Why is this?

  • First of all, for the first comparison, both d1 and d2 maintain permissions.
  • Then for the second comparison, d1 was passed to reduce the permissions. It could be modified originally, but now it cannot be modified; d2Passing it over becomes [amplification of authority]. The original d2 is const, but the this pointer is not added. [const] is modified, so it causes the problem of [permission method]

So how do you make a modification? At this time, you can use the [const member function] we mentioned above, and add a const to modify the current hidden parameter this . Do [permission maintenance]

bool operator<(const Date & d) const

Common interview questions for const member functions (key points!!)

Question 1:Can a const object call non-const member functions?

Of course not. As we have said before, if a const object calls a non-const member function, it will cause the phenomenon of [authority amplification]. Originally, the content of the const object outside the class cannot be modified, but when it comes to the function There are things that can be modified internally, but this is not allowed.

Question 2:Can non-const objects call const member functions?

Of course this is possible. The non-const object itself is readable and writable, so it will not affect whether you modify or not modify it inside the function

Question 3:Can other non-const member functions be called within a const member function?

No, only const member functions can be called within const member functions. Because the this pointer inside the const member function already has a constant attribute, problems will occur if the non-const member function modifies the content of the member variable.

Question 4:Can other const member functions be called within a non-const member function?

Yes, reduced permissions

Address and const address operator overloading

class Date
{
public:
    //Get address & reload
Date* operator &()
{
return this;
}
    //const takes address &overload
const Date* operator &()const
{
return this;
}
private:
int _year;
int _month;
int _day;
};

Of course, if we don’t write the & overload ourselves, the compiler will generate it by default. You can see it by printing:

Three, encourage each other

The following is my understanding of the default member function of the [C++] class – const member function. If there are friends who don’t understand and find problems, please tell them in the comment area, and I will also Continue to update your understanding of C++ classes and objects, please continue to follow me! ! !