Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you invoke an instantiated object's class constructor explicity in C++?

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?

like image 440
Lakshmi Avatar asked Nov 24 '08 11:11

Lakshmi


People also ask

Can a constructor be invoked when an object is created?

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.

What do we need to call constructor of a class during instantiation?

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.

Does base class constructor get called automatically?

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.

Can object class be instantiated directly?

You can invoke newInstance directly on the Class object if it has a public null constructor. (Null constructor is the constructor with no arguments.)


1 Answers

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.

like image 131
Michael Platings Avatar answered Sep 25 '22 00:09

Michael Platings