0
Is a globally declare function whose name is same as that of class can be a constructor in c++?
constructor in c++
2 Respuestas
+ 1
No, that cannot work.
I assume what you are proposing is this: In a class like this, where the normal default constructor is not defined on purpose:
class MyClass {
//MyClass(){..}
};
And instead you have some global function:
void MyClass(){..}
So, when you this:
MyClass* mc = new MyClass();
...the global function gets called instead?
The problem is that the global function will not know which instance of MyClass it has to operate on. When you see a constructor like this:
class MyClass {
MyClass(){..}
};
...the compiler does some "magic" and actually modifies that call to pass the 'this' pointer as the 1st argument when the constructor gets called (in this example the only argument since it is the default constructor):
class MyClass {
MyClass(/*hidden 'this' pointer here!*/){..}
};
This allows the constructor to update the data members of the specific instance (accessed through the 'this' pointer). In fact, the sole purpose of the constructor is to put the object (i.e. the instance) in a valid state, so it absolutely needs this 'this' pointer.
Static functions inside a class, OTOH, do not get the 'this' pointer when they are called, so they are more similar to global functions in that respect. But since static functions do not have access to the non-static data of a class (they would need the 'this' pointer for that), they would be completely useless as constructor since they would not be able to initialise the data members of the object to put the object in a valid state!
0
thank you Ettienne gilbert