Reputation: 69
Suppose I have class with two members,
class App
{
public:
App() : window(1366, 768, "Title"), drawer(window) {}
private:
Window window;
Drawer drawer;
}
and the Drawer class has constructor Drawer(const Window&)
.
Is it valid to initialize the App class member Drawer with the another class member Window, like in this example?
Upvotes: 2
Views: 85
Reputation: 26800
The non-static data members are initialized in order of declaration in the class definition. So in this particular instance it works as window
is declared before drawer
in the definition of App
.
But if you change the order, this will not work as intended.
But a compiler will warn you about this with appropriate warning level. GCC 8.2 with -Wall
option issues the following warnings if the order is reversed.
#1 with x86-64 gcc 8.2
<source>: In constructor 'App::App()':
<source>:16:14: warning: 'App::window' will be initialized after [-Wreorder]
Window window;
^~~~~~
<source>:15:14: warning: 'Drawer App::drawer' [-Wreorder]
Drawer drawer;
^~~~~~
<source>:13:4: warning: when initialized here [-Wreorder]
App() : window(1366, 768), drawer(window) {}
^~~
As drawer
is initialized first, it will not be initialized with the window
object that has been constructed with the values 1366 and 768.
Upvotes: 1
Reputation: 217275
Yes, following is valid:
class App
{
public:
App() : window(1366, 768, "Title"), drawer(window) {}
private:
Window window;
Drawer drawer;
};
Upvotes: 2