Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default constructor with empty brackets

People also ask

Can a default constructor be empty?

Providing an empty default constructor( private ) is necessary in those cases when you don't want an object of the class in the whole program. For e.g. the class given below will have a compiler generated default empty constructor as a public member . As a result, you can make an object of such a class.

What is called Empty constructor?

An empty constructor usually is "a default" Person() { // This will cause you to not have any name or age values }

What is empty constructor in C++?

Your empty constructor does not do what you want. The double data member will not be zero-initialized unless you do it yourself. The std::string will be initialized to an empty string. So the correct implementation of the default constructor would simply be C::C() : B() {} // zero-initializes B.

Does default constructor initialize 0?

As default constructor initializes the data members of class to 0.


Most vexing parse

This is related to what is known as "C++'s most vexing parse". Basically, anything that can be interpreted by the compiler as a function declaration will be interpreted as a function declaration.

Another instance of the same problem:

std::ifstream ifs("file.txt");
std::vector<T> v(std::istream_iterator<T>(ifs), std::istream_iterator<T>());

v is interpreted as a declaration of function with 2 parameters.

The workaround is to add another pair of parentheses:

std::vector<T> v((std::istream_iterator<T>(ifs)), std::istream_iterator<T>());

Or, if you have C++11 and list-initialization (also known as uniform initialization) available:

std::vector<T> v{std::istream_iterator<T>{ifs}, std::istream_iterator<T>{}};

With this, there is no way it could be interpreted as a function declaration.


Because it is treated as the declaration for a function:

int MyFunction(); // clearly a function
MyObject object(); // also a function declaration

The same syntax is used for function declaration - e.g. the function object, taking no parameters and returning MyObject


Because the compiler thinks it is a declaration of a function that takes no arguments and returns a MyObject instance.


You could also use the more verbose way of construction:

MyObject object1 = MyObject();
MyObject object2 = MyObject(object1);

In C++0x this also allows for auto:

auto object1 = MyObject();
auto object2 = MyObject(object1);

I guess, the compiler would not know if this statement:

MyObject object();

is a constructor call or a function prototype declaring a function named object with return type MyObject and no parameters.