Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there no call to the constructor? [duplicate]

Tags:

This code doesn't behave how I expect it to.

#include<iostream> using namespace std;  class Class {     Class()     {         cout<<"default constructor called";     }      ~Class()     {         cout<<"destrutor called";     } };  int main() {         Class object(); } 

I expected the output 'default constructor called', but I did not see anything as the output. What is the problem?

like image 789
mithilesh Avatar asked Sep 28 '10 07:09

mithilesh


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 C++ that statement makes a copy of the object's state. 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.

Does clone call constructor?

clone() doesn't call a constructor. You can only do this (unconditionally) if the class is final , because then you can guarantee to be returning an object of the same type as the original.


1 Answers

Nope. Your line Class object(); Declared a function. What you want to write is Class object;

Try it out.

You may also be interested in the most vexing parse (as others have noted). A great example is in Effective STL Item 6 on page 33. (In 12th printing, September 2009.) Specifically the example at the top of page 35 is what you did, and it explains why the parser handles it as a function declaration.

like image 184
JoshD Avatar answered Jan 02 '23 00:01

JoshD