Possible Duplicate:
Why is it an error to use an empty set of brackets to call a constructor with no arguments?
$ cat cons.cpp
#include <iostream>
class Matrix {
private:
int m_count;
public:
Matrix() {
m_count = 1;
std::cout << "yahoo!" << std::endl;
}
};
int main() {
std::cout << "before" << std::endl;
Matrix m1(); // <----
std::cout << "after" << std::endl;
}
$ g++ cons.cpp
$ ./a.out
before
after
$
What does the syntax Matrix m1();
do?
I believed that it is the same as Matrix m1;
. Obviously I am wrong.
The reason the copy constructor is not called is because the copy constructor itself is a function with one parameter. You didn't call such function,so it didn't execute.
In Java it simply copies the reference. The object's state is not copied so implicitly calling the copy constructor makes no sense. And that's all there is to it really.
A copy constructor is a member function that initializes an object using another object of the same class. The Copy constructor is called mainly when a new object is created from an existing object, as a copy of the existing object.
In Java, a constructor is the same as a method but the only difference is that the constructor has the same name as the class name. It is used to create an instance of the class. It is called automatically when we create an object of the class. It has no return type.
Matrix m1(); // m1 is a function whose return type is Matrix.
Also this C++ FAQ lite entry should be helpful.
Is there any difference between List x; and List x();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With