I was curious since I thought of the idea as a solution to improve the readability of my code for my assignment. When I create an object of a class, is there a way to call one of the object/class’ functions inside the constructor? If I’m not explaining myself clearly enough just ask and I’ll try to expound on it.
Share
Of course you can…
… But beware of virtual methods
There is only one catch, though: Avoid calling virtual methods as you won’t call the most derived method, only the most derived for that class. For example:
The output will be:
When you create a
Cobject, the constructors will be chained: FirstA(), thenB(), thenC(). And as we know by reading the code, theB()constructor callsfoo(), which is a virtual method.In C++, the method called by
B()will be thefoo()method which is:And for the current code, the right method is
B::foo().But why?
When you are executing the B constructor of the C object, only the A and B parts of C have been constructed. The C part isn’t constructed yet, so trying to access C’s data from B’s constructor would probably crash your code, and is a semantic error anyway.
So we must avoid that. The only normal way to access C’s data from one of the B’s methods is using virtual methods which are overridden by C.
So, to avoid that, virtual methods are not "fully resolved" in constructors and destructors (which suffer from the same problem, for the same underlying reasons).
Note that this C++ behavior is different from Java and C#’s.