Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are parent class constructors called before initializing variables?

Are parent class constructors called before initializing variables, or will the compiler initialize the variables of the class first?

For example:

class parent {
  int a;
public:
  parent() : a(123) {};
};

class child : public parent {
  int b;
public:
            // question: is parent constructor done before init b?
  child() : b(456), parent() {};
}
like image 951
user1810087 Avatar asked Mar 12 '13 16:03

user1810087


1 Answers

Yes, the base class is initialized before the members of the derived class and before the constructor body executes.

12.6.2 Initializing bases and members [class.base.init]

In a non-delegating constructor, initialization proceeds in the following order:

— First, and only for the constructor of the most derived class (1.8), virtual base classes are initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where “left-to-right” is the order of appearance of the base classes in the derived class base-specifier-list.

— Then, direct base classes are initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).

— Then, non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).

— Finally, the compound-statement of the constructor body is executed.

like image 180
Luchian Grigore Avatar answered Sep 22 '22 06:09

Luchian Grigore