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?

3
  • 1
    Yes p gets automatically default initialised. Why do you think it doesn't? You might also want to learn about member initialiser lists. That link also covers initialization order.
    – john
    Aug 22, 2020 at 6: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 Students constructor is entered).
    – Peter
    Aug 22, 2020 at 7:17
  • This kind of questions should be covered by reading a good book (The Definitive C++ Book Guide and List)
    – t.niese
    Aug 22, 2020 at 7:43

1 Answer 1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.