Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how memory is allocated for a c++ program

Tags:

c++

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:

  1. In which sequence memory is allocated for data members('s' in this case).
  2. Does Object exist while calling fun() in the constructor.

My doubt is how I am calling a function on the b object which is not yet created by the constructor.

like image 350
arvind Avatar asked Jun 16 '26 04:06

arvind


1 Answers

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.

like image 60
bipll Avatar answered Jun 17 '26 23:06

bipll