Consider the below program:
#include <string>
#include <iostream>
class B {
private:
std::string s;
public:
B() { s = fun(); }
std::string fun() { return "hello"; }
void print() {
std::cout << s;
}
};
int main(){
B b;
b.print();
}
The output is Hello
My Questions are:
My doubt is how I am calling a function on the b object which is not yet created by the constructor.
By the moment object's constructor body starts executing, all the object's bases, direct, or, consequently, indirect, and members have already been initialized, either explicitly or implicitly. So s is a valid string object that can be quite legally a LHS of an assignment.
One thing should probably be noticed here is, if you call a polymorphic class's virtual method from your constructor, then this, current, type's implementation is chosen, as any derived type has not been initialized yet so its overloads, if any, would be illegal to call.
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