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.
What do you mean "what does c++ do"?
in the main I only instantiate an instance of the class using the parameter based constructor, what does c++ do ?


It instantiates the object, using the parameter based constructor.
It would invoke the requested constructor, and return the constructed object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
 
class Type {
public:
    Type(): msg("Hello, world!") {}
    Type(const char *msg): msg(msg) {}
 
    friend std::ostream &operator<<(std::ostream &out, Type obj) {
        out << obj.msg;
        return out;
    }
 
private:
    const char *msg;
};
 
int main() {
	Type obj1;
	Type obj2("Goodbye, world!");
 
	std::cout << obj1 << ' ' << obj2 << '\n';
}


Hello, world! Goodbye, world!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

class T
{
public:
    T() { cout << "I am constructed by the default constructor.\n"; }
    T(int x) { cout << "I am constructed by the parameter based constructor.\n"; }
};

int main()
{
    T t1;   // object of type T declared, no match with any defined constructors,
            // use the default constructor.
    T t2{ 5 }; // c++ will call the parameter based constructor.

    system("PAUSE"); // wait for the user to press enter
}


If you compile and execute that, you will see that c++ will call the constructor based on your declaration.
Last edited on
> T t1; // object of type T declared, no match with any defined constructors,

it does match a defined constructor. the first one you defined.
Last edited on
Ok cool, thanks for all the answers. I understand now.
Topic archived. No new replies allowed.