Constructors

In c++ if I define a class to have a default constructor as well as a parameter based constructor but in the main I only instantiate an instance of the class using the parameter based constructor, what does c++ do ?

Just curious as to what would happen and can't find an answer anywhere.
-----------------------------------------
Công ty <a href="https://ruthamcau.suu.vn/rut-ham-cau-tai-cac-quan-tphcm.html">rut ham cau gia re</a> giá rẻ dịch vụ <a href="https://ruthamcau.suu.vn/rut-ham-cau-tai-cac-quan-tphcm.html">rút hầm cầu giá rẻ</a> tận tâm
Last edited on
If you have a default constructor and user defined constructor, but initiate an object with the user-defined constructor, the user-defined constructor will be called instead of the default constructor.

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
#include <iostream>

class myclass
{
    public:
        int get() const;
        myclass();
        myclass(const int set_x);
    private:
        int x;
};

int myclass::get() const
{
    return x;
}

myclass::myclass()
{
    std::cout << "Default constructor called\n";
}

myclass::myclass(const int set_x)
{
    x = set_x;
}

int main()
{
    myclass object(100); /* The default constructor will not be called here */
    std::cout << object.get() << std::endl;
    return 0;
}
Look at the C++14 tab in http://www.cplusplus.com/reference/vector/vector/vector/
The std::vector seems to have 10 constructors. Is that more complex than with two constructors? No.

C++ has function overloading. There can be more than one function with identical name, but different parameters. When the name is used (a function is called), the compiler searches from the list of declared names the one that matches best to the parameter types. Implicit conversions of the parameters are allowed (unless constructor declaration requires explicit types).

Lets add to the fiji885's example:
1
2
3
4
int main() {
  double bar { 3.14 };
  myclass foo( bar );
}

The declaration of foo seems to require myclass::myclass(double)
However, the available declarations are:
1
2
3
myclass::myclass() #1
myclass::myclass(const int) #2
myclass::myclass(const myclass&) #3 

The #3 is copy constructor, which the compiler automatically generates (except in special cases).

Can the compiler match any of these to the actual call?
There is no direct match, but compiler can add some implicit conversions.
Is there an unambiguous winner then?

Yes, casting double into int makes #2 a valid choice.
There is no cast from double to nothing (except in game shows).
Casting from double to myclass is the whole dilemma, so #3 is out.

Therefore, the compiler inserts call to myclass::myclass(const int).


PS. C++11 did add delegating constructor syntax. With that one constructor can call an another constructor of the same class.
Topic archived. No new replies allowed.