1

I want to know if a class contains an object of another class and both classes have constructors, how does initializing in the constructor in the class that contains the object of another class work. and what is the order of initialization?

class Person
{
    string name;
    int age;
  public:
    Person()
    {
        name="NULL";
        age=0;
    }
};


class Student
{
    int roll_no;
    Person p;
    int division;
   public:
        Student()
        {
            roll_no=0;
            division=0;
        }
};

In this example, in the student class constructor, do we need to put code like

Student()
{
    roll_no=0;
    p.Person();
    division=0;
}

Do we need to put p.Person(); to initialize p? Doesn't p automatically get initialized when it is created because it has a constructor. what is the order of initializing through constructors in cases like this?

  • 1
    Yes `p` gets automatically default initialised. Why do you think it doesn't? You might also want to learn about [member initialiser lists](https://en.cppreference.com/w/cpp/language/constructor). That link also covers initialization order. – john Aug 22 '20 at 06:52
  • 1
    When constructing a `Student`, its member `p` will be default initialised (i.e. using its constructor that accepts no arguments) before the constructor of `Student` is entered. You could make things more explicit by defining the constructor as `Student() : p() {roll_no = 0; division = 0;}` (this ignores the fact that `roll_no` and `division` are also default-initialised before the body of `Student`s constructor is entered). – Peter Aug 22 '20 at 07:17
  • This kind of questions should be covered by reading a good book ([The Definitive C++ Book Guide and List](https://stackoverflow.com/questions/388242)) – t.niese Aug 22 '20 at 07:43

1 Answers1

2

Do we need to put p.Person(); to initialize p?

No, and you can't do that. The initialization order is:

  1. ...
  2. ...
  3. Then, non-static data member are initialized in order of declaration in the class definition.
  4. Finally, the body of the constructor is executed

For example, when an object of type Student is default-initialized, the member roll_no is default-initialized firstly, then p is default-initialized via the default constructor of Person, then division is default-initialized, at last the default constructor of Student is invoked and roll_no and division get assigned.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405