When you have more complex types, and you use the second method, the Objects are created with the default constructor and then you change it's members which takes more time because you basically initialize the Object twice.
When you have more complex types, and you use the second method, the Objects are created with the default constructor and then you change it's members which takes more time because you basically initialize the Object twice.
please correct me if I'm wrong
That's correct - although it's more precise to say you're initialising it once and then assigning new values to it.
#include<iostream>
class A
{
private:
int x;
public:
// class A has only a 1 arg ctor.
A( int X ) { x = X; }// 2nd method OK. type int is basic
};
class B
{
private:
double& rd;// reference member
A a;// member with no no-arg ctor
public:
B( int X, double & rDbl ): rd(rDbl), a(X) {}// must use initializer list for these 2 members
// B( int X, double & rDbl ) { rd = rDbl; a.x = X; }
double& get_ref(){ return rd; }// added to show use of refernce member in main()
};
int main()
{
double dblVar = 3.14;
B b( 5, dblVar );
b.get_ref() = 7.77;// assign new value through b's reference to dblVar
std::cout << "dblVar now = " << dblVar << '\n';
return 0;
}
The example compiles and runs as is.
A 2nd B class ctor is commented out. Change to this from the 1st ctor for errors.
I get the following:
D:\my_programs\codeBlocksProjects\forumProbs\main.cpp||In constructor 'B::B(int, double&)':|
D:\my_programs\codeBlocksProjects\forumProbs\main.cpp|28|error: uninitialized reference member in 'double&' [-fpermissive]|
D:\my_programs\codeBlocksProjects\forumProbs\main.cpp|24|note: 'double& B::rd' should be initialized|
D:\my_programs\codeBlocksProjects\forumProbs\main.cpp|28|error: no matching function for call to 'A::A()'|
D:\my_programs\codeBlocksProjects\forumProbs\main.cpp|28|note: candidates are:|
D:\my_programs\codeBlocksProjects\forumProbs\main.cpp|18|note: A::A(int)|
D:\my_programs\codeBlocksProjects\forumProbs\main.cpp|15|error: 'int A::x' is private|
D:\my_programs\codeBlocksProjects\forumProbs\main.cpp|28|error: within this context|
That last error provides a 3rd reason, which I hadn't thought of.
Assigning a.x = X; in the body of the ctor is illegal because A::x is private.