The basics of programming in c++ for beginners

The overloaded constructor

The article The constructor and destructor of the class We have already met with the overloaded constructor in the code, but not focused on this note. Overloading constructors are very similar to overload functions. Designers in the defined class may be several – as needed. They should have the same name, identical to the name of the class and necessarily the signature must be different.

For example: one of the designers takes no parameters, the second takes two parameters, the third takes three parameters. Later, during object creation, parameters are passed as arguments. Since the compiler can determine, which of the declared constructors to use when creating an object.

Consider the example:

overloaded constructor c ++, basics of programming for beginners, c++ from scratch This example is easy enough to see, what caused the need to overload constructors. The main point is, to enable the programmer to choose the most appropriate way to initialize the object.

Here it is presented the most common variant of designers overload. Namely, the constructor with parameters, and a second without parameters. Often, programmers are needed both of these designer, as the constructor parameters useful, working with individual objects. But it can not be used, for example, to initialize a dynamic array class facilities.

Each object class declaration is necessary to apply an appropriate way to certain designers Ad.

The constructor can be overloaded many times, as you see fit. But, as happens in most cases,, it is desirable to adhere to the golden mean. Overload it only for the most common situations.

I would like to add, destructor, unlike designer, It can not be overloaded, since it does not take any parameters.

2 thoughts on “The overloaded constructor

  1. It would be good to add:
    – If you are describing a class without a constructor general description, the class is created by the default constructor without parameters;
    – but as soon as you add at least one constructor, silent no-argument constructor is not created too (it can then puzzle for creating objects);
    – if still needed, and the constructor without parameters, including, it must be clearly described.

    And further…
    Often, instead of descriptions of several designers to create a comfortable one constructor, but with several parameters, with certain default values:

    class my {
    my( int first = 0, float second = 1.0, char *title = "object" ) {
    // ...
    }
    }
    ...
    my m1(), m2( 3 ), m3( 4, -5.5 ), m4( 5, 1.0, "new_object" );

  2. At the time, confusing the word “overloaded”-Why it overload, Why so disliked? Then he explained himself, it is rebooting.

Leave a Reply

Your email address will not be published. Required fields are marked *