Reading Notes in C ++ meditation-Reflection on classes

Source: Internet
Author: User

The concept of class is nothing more than a collection of data and methods. Why have I been confused? Why not?

The class concept in C ++ has four special functions. People like me who have C experience may not be able to adapt at the moment, they are constructor, destructor, copy constructor, and assign value operator.

These four functions have their own uniqueness, which is confusing. After reading "C ++ meditation" this time, I will organize it and share it with you.

1. Why do we need a constructor?

Some classes are very simple and require no constructor at all, so not all classes require constructor. However, for some complex classes, they need constructors to hide their internal working methods. In this case, they need to create one.


2. Why are some data private, some public, and the same method?Public-modified data and methods can be accessed by anyone. If you need to control access to the data or some methods, it is best to use the domain modifiers public, protect, and private to restrict access. There is a good description in "C ++ meditation", which shows that our access to private variables can be different from the general practice. For example, for example, when reading a private variable, a function is usually written to return this private variable, but have you thought about other methods, for example, the following implementation uses a const reference to read:
/* An example shows why the const reference of the getLength () function can be implemented without a binding, however, it is slightly troublesome to add a sentence in the initialization table of each constructor */class Stick {public: const int & length; // reference a const, stick (): true_length (1), length (true_length) {} Stick (Stick & st): true_length (st. true_length), length (true_length) {} Stick (int a): true_length (a), length (true_length) {} void setLength (int B) {true_length = B ;} // int getLength () {return true_length;} private: int true_length ;};


3. Why do I need a constructor without parameters?

Many times, when I write a constructor that I think is required, I always add a constructor without parameters, but I seldom wonder why I need such a constructor without parameters, what functions does it bring to me? In fact, a non-argument constructor allows you to define class Stick a like this. If Stick does not have a constructor without parameters, such a definition is wrong, when you need an array of Stick, if there is no parameter constructor, it cannot be successful, and there are many array definitions, such as Stick a [1024]; but I seldom think about what else there is a no-argument constructor here.


4. Do I need to initialize all data members in the constructor?

The object-oriented design uses classes to encapsulate the state. Although this design also has its own shortcomings, the object does reflect the State through data members. Do all data members have an initial state? This is not necessarily the case, so in my opinion, when you initialize it before use, it will be OK, or even if it is not initialized, it will be OK.


5. Do classes require destructor?

It may be silly to ask this question than to ask the constructor, but in fact the Destructor is closely related to the data members of the class, and not all classes need the destructor. Only when your class applies for resources and these resources are not automatically released through the member functions, you need an destructor to wipe your ass.


6. Do classes need a virtual destructor?I hesitated while taking notes, because I still have a deep understanding of the virtual function. First, the role of a virtual function is only embodied when it is inherited. Therefore, when a class may become a parent class, the virtual function has a role. Therefore, if your class requires a virtual function, the class will become the parent class first, otherwise you will write it in white. So what is the role of a virtual destructor? I didn't talk about it in the book. I just gave an example. Let's take a look at the example first. Assume that there is a parent class B, subclass D inherits from parent class B, and then a parent class pointer is used to analyze the Child class, as shown below:
class B {public:    int s;};class D: public B {public:    int t;    ~D() { printf("~D\n"); }};int _tmain(int argc, _TCHAR* argv[]){    B *bp = new D;    delete bp;    return 0;}

Here I have defined a destructor for D and printed it, just to show whether the Destructor for D has been called. The fact is no, that is to say, if the parent class does not define the destructor, a parent class pointer pointing to the subclass will not call the destructor of both the parent class and the subclass. Similarly, if the destructor of the parent class is not a virtual function, it does not call the destructor of the subclass, but directly calls the destructor of the parent class. Therefore, to complete the Destructor call chain and enable the sub-class destructor to be called, the parent class destructor must be defined as virtual. But not all destructor of the parent class must be virtual functions? This is also unknown. There are several words circulating between our company's tests: If we can see that the destructor of the parent class are not defined as virtual functions, then we will smile and say another bug; if your class has a virtual function, the Destructor must also be virtual.

In Article 7 of the third edition of Objective C ++, there is a saying that "any class with a virtual function is almost sure that there should also be a virtual destructor ", I think the above slogans are probably from here. However, if my class is a parent class, it will not use a parent class pointer as above to release the subclass, that is, it will not have the characteristics of polymorphism, therefore, it is unreasonable to require the parent class to have virtual destructor. In the book "C ++ meditation", I also said, "making all classes automatically contain virtual destructor will kill C ++ 'only pay the price for what is used' philosophy ".

In conclusion, the parent class must define a virtual destructor only when you want to use the polymorphism feature. The Calling sequence of destructor is not described here. It is actually very simple. google it yourself.


7. When do I need a replication constructor?

Before explaining this problem, we may need to understand that if you do not define a replication constructor, the compiler will automatically add a replication constructor for you. In fact, the compiler will not only automatically add the copy constructor, but also add the value assignment operator, destructor, and even constructor without definition, for more information, see Objective C ++. The copy constructor added by the compiler directly copies the data members and base class objects. If you do not want to do so, you have to define a copy constructor to prevent the one added by the compiler. For example:

class String {public:    String();    String(const char *s);private:    char *data;};

If the definition of such a class does not define the replication constructor, the compiler will add one, but this will cause the data address to be saved in more than one object when copying this class, the data may be released multiple times, so it is extremely dangerous to define a replication constructor for this class. What should you do if you want to stop copying objects? C ++ meditation records provides an approach to define the replication constructor as private, and ensure that your member functions will not be useful in copying objects:

class String {public:    ......private:    String(const String &);    String &operator=(const String &);    ......};


8. When do I need a value assignment operator?

This is a simple reason. You need to define an object when copying an object using the value assignment operator. Note that the value assignment operator is called only after the object has been constructed, what does this mean? See the following example:

class A {public:    A() {}    ~A() {}    A(const A &) { printf("copy construct\n"); }    A &operator=(const A &) { printf(" = operator\n"); return *this; }};int _tmain(int argc, _TCHAR* argv[]){    A a;    A b(a);    A c = a;    A d;    d = a;    return 0;}

Here, only the last d = a; will call operator = (), A B (a); and A c = a; both call the copy constructor, which is easy to understand, why does A c = a; also call the copy constructor? In fact, this writing method is just a syntactic sugar to be compatible with C. What else can be said about the value assignment operator? Of course, when you assign a value to yourself, you need to pay attention to this behavior. Before assigning a value, you should first determine whether you have assigned a value to yourself and then process it.


This article from the "cainiao surfaced" blog, please be sure to keep this source http://rangercyh.blog.51cto.com/1444712/1287993

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.