Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Is it possible to call an object's function before constructor completes?

In C++, is it possible to call a function of an instance before the constructor of that instance completes?

e.g. if A's constructor instantiates B and B's constructor calls one of A's functions.

like image 863
Jonathan Livni Avatar asked Oct 14 '10 17:10

Jonathan Livni


People also ask

Can you call a function within a constructor?

You can call a virtual function in a constructor. The Objects are constructed from the base up, “base before derived”.

Can we call member function using this pointer from constructor?

the constructor is the first function which get called. and we can access the this pointer via constructor for the first time. if we are able to get the this pointer before constructor call (may be via malloc which will not call constructor at all), we can call member function even before constructor call.

Can we call a method from constructor in C++?

A constructor can call methods, yes. A method can only call a constructor in the same way anything else can: by creating a new instance.


1 Answers

Yes, that's possible. However, you are responsible that the function invoked won't try to access any sub-objects which didn't have their constructor called. Usually this is quite error-prone, which is why it should be avoided.

like image 115
sbi Avatar answered Sep 20 '22 00:09

sbi