Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the constructor not called when () is used to declare an object? [duplicate]

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.

like image 250
Lazer Avatar asked Feb 26 '12 07:02

Lazer


People also ask

Why is my copy constructor not being called?

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.

Why there is no copy constructor in Java?

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.

Why is copy constructor called?

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.

Does copy constructor has return type?

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.


1 Answers

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();

like image 190
Mahesh Avatar answered Sep 20 '22 15:09

Mahesh