After creating a instance of a class, can we invoke the constructor explicitly? For example
class A{
A(int a)
{
}
}
A instance;
instance.A(2);
Can we do this?
A constructor is similar to method and it is invoked at the time creating an object of the class, it is generally used to initialize the instance variables of a class. The constructors have same name as their class and, have no return type.
When you create an object, you are creating an instance of a class, therefore "instantiating" a class. The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate. The constructor initializes the new object.
Using your example, the answer is: YES. The base constructor will be called for you and you do not need to add one. You are only REQUIRED to use "base(...)" calls in your derived class if you added a constructor with parameters to your Base Class, and didn't add an explicit default constructor.
You can invoke newInstance directly on the Class object if it has a public null constructor. (Null constructor is the constructor with no arguments.)
You can use placement new, which permits
new (&instance) A(2);
However, from your example you'd be calling a constructor on an object twice which is very bad practice. Instead I'd recommend you just do
A instance(2);
Placement new is usually only used when you need to pre-allocate the memory (e.g. in a custom memory manager) and construct the object later.
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