Why do I receive the error below? (Why is the compiler trying to call the default constructor?)
#include <cmath>
template<typename F> struct Foo { Foo(F) { } };
int main()
{
Foo<double(double)>(sin); // no appropriate default constructor available
}
A default constructor is a constructor created by the compiler if we do not define any constructor(s) for a class. Here is an example: public class Student { String firstName; String lastName; int age; public static void main(String args[]) { Student myStudent = new Student(); myStudent.
The Java compiler provides a default constructor if you don't have any constructor in a class. The method is not provided by the compiler in any case. The constructor name must be same as the class name.
No, the C++ compiler doesn't create a default constructor when we initialize our own, the compiler by default creates a default constructor for every class; But, if we define our own constructor, the compiler doesn't create the default constructor.
In both Java and C#, a "default constructor" refers to a nullary constructor that is automatically generated by the compiler if no constructors have been defined for the class. The default constructor implicitly calls the superclass's nullary constructor, then executes an empty body.
It is because there is no difference between
Foo<double(double)>(sin);
and
Foo<double(double)> sin;
Both declare a variable of name sin
.
The parens are superfluous. You can put as many parens as you want.
int x; //declares a variable of name x
int (x); //declares a variable of name x
int ((x)); //declares a variable of name x
int (((x))); //declares a variable of name x
int (((((x))))); //declares a variable of name x
All are same!
If you want to create temporary instance of the class, passing sin
as argument to the constructor, then do this:
#include<iostream>
#include <cmath>
template<typename F>
struct Foo { Foo(F) { std::cout << "called" << std::endl; } };
int main()
{
(void)Foo<double(double)>(sin); //expression, not declaration
(Foo<double(double)>(sin)); //expression, not declaration
(Foo<double(double)>)(sin); //expression, not declaration
}
Output:
called
called
called
Demo : http://ideone.com/IjFUe
They work, because all three syntaxes force them to be expressions, rather than variable declarations.
However, if you try this (as @fefe sugguested in the comment):
Foo<double(double)>(&sin); //declaration, expression
It is not going to work, for it declares a reference variable, and since it is not initialized, you will get compilation error. See : http://ideone.com/HNt2Z
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