I don't understand what does "the constructor is called implicitly by C++" means.
I mean what is different between calling implicitly or explicitly?
Thanks
Printable View
I don't understand what does "the constructor is called implicitly by C++" means.
I mean what is different between calling implicitly or explicitly?
Thanks
My guess is that it means that say:
Invokes the default constructor for class A even though it does not look like a function call, as opposed to explicitly calling the constructor with:Code:A a; // Invoke the default constructor to instantiate an A object named a.
Then there are other circumstances where invoking the constructor looks a little like a function call because of the parentheses, but otherwise is not proper function call syntax.Code:a.A(); // Imaginary syntax for an explicit constructor call for class A.
That's a poor way to phrase it. A Constructor is called intentionally, whether you've coded one up or not, when a object is instantiated. There's the default constructor that you don't have to code, or you can code one up to do additional stuff.Quote:
"the constructor is called implicitly by C++"
So, perhaps it should say "the Constructor is automatically called by C++ when an instance is created" or something like that.
Todd
The explicit keyword can be used on constructors to force explicit use of the constructor. For example:
Code:class Data_Implicit
{
public:
Data_Implicit(int data) : data_(data) { }
int data_;
};
class Data_Explicit
{
public:
explicit Data_Explicit(int data) : data_(data) { }
int data_;
};
void FooImplicit(Data_Implicit di)
{
std::cout << di.data_;
}
void FooExplicit(Data_Explicit de)
{
std::cout << de.data_;
}
int main()
{
FooImplicit(3);
FooExplicit(3); // compiler error... trying to call explicit constructor implicitly
FooExplicit(Data_Explicit(3)); // ok explicit call to constructor made.
}