I came across this where one of the user comment says:
A constructor cannot be called, it is not a function. It is invoked automatically when a new object is created.
My question is that is the above comment true/correct? If yes, then why isn't a constructor considered a function and why can't we call it.
CodePudding user response:
Formally in the C Standard it is (along with several others) a special member function so yes it is a function, but it is a special function and not all of the normal rules apply.
There is no syntax to write code that calls a constructor directly or forming a function pointer to it. The compiler will automatically call a constructor when an object is created. The compiler will also automatically call constructors for subobjects (bases and members) of a class object. "Delegating constructors" are sort-of a degenerate case of initialization of subobjects (In formal algebra, we say that any set is a subset of itself, and say "strict" subset when we mean a subset that is not the entire set).
There are a variety of ways to create an object and some of them look like a function call, but that's actually a cast and results in creation of a new object, on which the constructor is called implicitly by the compiler. There's also placement-new syntax which doesn't do very much besides causing the compiler to implicitly call the constructor -- but even there a brand new object is being created.
One important way in which the compiler's implicit call to a constructor differs from an explicit function call found in user code is that the implicit call occurs within an implicit try/catch scope that will result in destruction of subobjects if an exception occurs. A direct call to the constructor, if one were possible, wouldn't have such extra behavior.
CodePudding user response:
The quoted comment is incorrect. A constructor is a special member function. And it can be implicitly called by the compiler at the time of object creation.
For example,
struct A
{
};
int main()
{
//----v----->note the absence of parenthesis like when we call a function
A a; //creates object of type A by implicitly calling the default constructor
}