This question already has answers here:
C++: When (and how) are C++ Global Static Constructors Called?
(5 answers)
Closed 3 years ago.
This some code I wrote:
#include <iostream>
class Number
{
int n;
public:
Number(int n)
{
std::cout << "Constructed object: " << n << std::endl;
this->n = n;
}
};
Number b = 2; //when does this ctor get called?
int main()
{
Number a = 4;
}
Output:
Constructed object: 2
Constructed object: 4
When does the constructor of the global object get called? Right before main is executed?
When does the constructor of the global object get called? Right before main is executed?
Essentially, yes. Within a translation unit, objects are constructed in the order that they appear. Across translation units, the order is undefined.
Objects are destroyed in the opposite order to their construction.
For gcc (and I think, also, clang), see also: How exactly does __attribute__((constructor)) work?
yes, the constructor of the global object gets called before main()
for additional information:
here I'm listing when the constructors gets called for different types of object like global, local,static local,dynamic
1)for global object you already wrote a program
2)For a non-static local object, constructor is called when execution reaches point where object is declared
using namespace std;
class Test
{
public:
Test();
};
Test::Test() {
cout << "Constructor Called \n";
}
void fun() {
Test t1;
}
int main() {
cout << "Before fun() called\n";
fun();
cout << "After fun() called\n";
return 0;
}
/* OUTPUT:
Before fun() called
Constructor Called
After fun() called
*/
For a local static object, the first time (and only the first time) execution reaches point where object is declared.
3)Class Scope: When an object is created, compiler makes sure that constructors for all of its subobjects (its member and inherited objects) are called. If members have default constructurs or constructor without parameter then these constrctors are called automatically, otherwise parameterized constructors can be called using Initializer List.
// PROGRAM 1: Constrcuctor without any parameter
#include<iostream>
using namespace std;
class A
{
public:
A();
};
A::A() {
cout << "A's Constructor Called \n";
}
class B
{
A t1;
public:
B();
};
B::B() {
cout << "B's Constructor Called \n";
}
int main() {
B b;
return 0;
}
/* OUTPUT:
A's Constructor Called
B's Constructor Called
*/
Related
I read in http://www.cs.technion.ac.il/users/yechiel/c++-faq/init-lists.html
that using initializer lists is more efficient than doing assigment in the body of the constructor, because for example in Fred::Fred() { x_ = whatever; }
1) the expression whatever causes a separate, temporary object to be created, and this temporary object is passed into the x_ object's assignment operator. Then that temporary object is destructed at the ;
2)the member object will get fully constructed by its default constructor, and this might, for example, allocate some default amount of memory or open some default file
How can assigment cause the creation of some temporary object inside the constructor? That means that the Construtor would call itself: an infinite recursive call
I made the following piece of code to verify a copy of the object is created in the assigment process,hoping to see the additional creation and destruction of the temporary object but all I can see is the creating and destruction of the object I am creating in the main an of course no infinite recursive call.
How do I make sense of it and how can I modify the code to see the creation and destruction of the temporary object?
#include<iostream>
using namespace std;
class Base
{
private:
int c_var;
public:
Base( )
{ c_var=10;
cout <<"Constructor called"<<endl;
cout << "Value is " << c_var<<endl;
}
~Base()
{
cout <<"Destructor called"<<endl;
}
};
int main()
{
Base il;
}
How can assigment cause the creation of some temporary object inside the constructor? That means that the Construtor would call itself: an infinite recursive call
No. The text talks about calling the constructor of the member. With an int it doesn't matter too much, but consider:
struct foo {
foo() {
/* construct a foo, with expensive instructions */
std::cout << "default constructor";
}
foo(int x) {
/* also construct a foo */
std::cout << "constructor";
}
};
struct bar_wrong {
foo f;
bar_wrong() {
f = foo(42);
}
};
Members are initialized before the body of the constructor is executed. Hence the foo member of bar_wrong will first be default constructed (which is potentially expensive) just to be overwritten with the right instance later and creating a bar_wrong will print both outputs from foos constructors.
The correct way is
struct bar_correct {
foo f;
bar_correct() : f(42) {}
};
Because here foo is only initialized. Alternatively you can use in-class initializers:
struct bar_alternative {
foo f{42};
};
Here the compiler generated constructor is sufficient. It will use the in-class initializer to initialize f with 42.
Lets say I have 2 diffrent classes.
Why when I put class A object as data member inside class B, the class that getting destroyed first is class B and then class A but when i put class A object in the builder of class B then class A getting destroyed first and then class B? for example:
class A {
public:
~A() { std::cout << "Deleting A\n"; }
};
class B {
private:
A object;
public:
~B() { std::cout << "Deleting B\n"; }
};
int main( void ) {
B test;
return 0;
}
result:
Deleting B
Deleting A
But the next example gives me the opposite result :
class A {
public:
~A() { std::cout << "Deleting A\n"; }
};
class B {
public:
B() { A object; }
~B() { std::cout << "Deleting B\n"; }
};
int main( void ) {
B test;
return 0;
}
result:
Deleting A
Deleting B
In your second example B test; calls the constructor of B.
The constructor B is just a function and it has a local variable A object;. This object is created and at the end of the scope (end of the constructor of B) it is detroyed.
Back in main at the end of main the object test is destroyed.
So in that case the object A object; is destroyed first, later object B test; is destroyed.
In your first example this is something different. There A object; is a member of class B, so the constructor of B is constructing the member automatically. The order of construction is: base classes first (not present in your example), then members, then the body of the constructor. Destruction is the opposite order: body of the destructor first, then the members (including your A object;), then the base classes (not present in your example).
As already said in a comment, you can easily step through the code in a debugger to get a better understanding of the order of execution.
Because the object of class A is destroyed as soon the constructor of class B finishes (because it is a local variable inside a function) and it is before the class B destructor be called.
In the second example you've got your object (instance of Class A), local in your Constructor. When you now instantiate B in your main function, the constructor is called, creates object, and destroys it, as sonn as the constructor has finished.
In your first example, object is a class member and lives as long as your class object in your main function. When the programm is finished it calls your costum Destructor, this is then executed first, then it destructs all members (standard Constructor).
This question already has answers here:
C++ Default Constructor Called
(3 answers)
Closed 4 years ago.
Okay, first off this is a trivial question, but nonetheless it's bugging me. Disclaimer: I'm not a compiler engineer. But it seems to me the compiler in this case is requiring a constructor that is really not necessary. Code below; why is the B constructor that takes no parameters and does nothing being called when an already instantiated object of it's class is being passed to the constructor of another class? For reference I'm using g++ (GCC) 5.3.0 and have not tried it with any other compilers (and yeah I know GCC is not without its quirks):
#include <iostream>
namespace I_DO_NOT_GET_IT
{
class A;
class B;
}
class B
{
public:
B()
{
std::cout << "\nWhy am I here?\n\n";
}
B(const int aInt, const char * aChar)
{
mInt = aInt;
mChar = aChar;
}
void identify()
{
std::cout << "\nI am an object of class B, owned by class A\n"
<< "my integer data is "
<< mInt
<< " and my character data is \""
<< mChar
<< "\"\n\n";
}
int mInt;
const char * mChar;
};
class A
{
public:
A(B an_instantiated_object_of_class_B)
{
b = an_instantiated_object_of_class_B;
}
// class A owns an object of class B
B b;
};
int main()
{
// create an object of class B
B b(1, "text");
// pass the B object to A, which uses it to instantiate its B object
// in the A constructor.
A a = B(b);
// Have A's B object describe itself
a.b.identify();
return 0;
}
A(B an_instantiated_object_of_class_B)
{
b = an_instantiated_object_of_class_B;
}
The default constructor of B is used when A::b is created before the constructors body runs, where an assignment b = ... occurs.
Use the initialization list instead:
A(B an_instantiated_object_of_class_B)
: b{ an_instantiated_object_of_class_B }
{
}
btw, your namespace I_DO_NOT_GET_IT is pointless. The declarations in there have nothing to do with your classes A and B.
Consider the following code
#include <iostream>
using namespace std;
class A
{
int x;
public:
A() { cout << "A's constructor called " << endl; }
};
class B
{
public:
static A a;
B() { cout << "B's constructor called " << endl; }
static A getA() { return a; }
};
A B::a; // definition of a
int main()
{
B b1, b2, b3;
A a = b1.getA();
cout<<&a<<endl;
cout<<&B::a;
return 0;
}
the output is
A's constructor called
B's constructor called
B's constructor called
B's constructor called
0x7fff03081280
0x601194
Now lets consider another similar code
#include <iostream>
using namespace std;
class A
{
int x;
public:
A() { cout << "A's constructor called " << endl; }
};
class B
{
public:
static A a;
B() { cout << "B's constructor called " << endl; }
static A getA() { return a; }
};
A B::a; // definition of a
int main()
{
B b1, b2, b3;
A a ;
a= b1.getA();
cout<<&a<<endl;
cout<<&B::a;
return 0;
}
the output is
A's constructor called
B's constructor called
B's constructor called
B's constructor called
A's constructor called
0x7ffc485a1070
0x601194
Now my question is that why in the first case the constructor of A is called only once , whereas in the second code its called twice.
Also the two output &a and &B::a are different so it means they are two different objects .
Please explain why this is so.
In your first code
A a = b1.getA();
the copy-constructor of A gets called which doesn't generate any output. Define it yourself and you'll get a similar output to your second code.
Hmm, B::a is B's (public) static member instance of otherwise quite an usual class A. So, the first A's constructor logged is that of B::a, which should be initialized before control enters main, but next you create a separate instance of A local to main, it is constructed in order alongside with other main's local variables (here, right after all the Bs) and it is naturally distinct from B::a.
Now my question is that why in the first case the constructor of A is called only once , whereas in the second code its called twice.
Because in the first case you default-initialised only the static B::a, and copy-initialised the local a.
In the second you default-initialised both objects.
The crucial difference is that you only print a message in the default constructor, and don't print anything in the copy constructor.
Also the two output &a and &B::a are different so it means they are two different objects .
That is correct. a is a local variable, while B::a is a static member variable. They are different objects.
Static member variables of class type represent a storage with process-wide life span. It gets initialized as such, at some point before entry point to program - the beginning of main() - is reached. That's the first constructor call.
The line
A a = b1.getA();
initializes object a by calling copy constructor and through return value optimization and copy elision there is no default constructor call.
The second variant:
A a; // A() call
a = b1.getA(); // operator= call
Modified class
class A
{
int x;
public:
A(const A& a): x(a.x) { cout << "A's copy constructor called " << endl; }
A(A&& a): x(a.x) { a.x = 0; cout << "A's move constructor called " << endl; }
const A& operator=(const A& a) { x = a.x; cout << "A's copy operator= called " << endl; }
A() { cout << "A's constructor called " << endl; }
};
would give this output in first case:
A's constructor called
B's constructor called
B's constructor called
B's constructor called
A's copy constructor called
And second case would result in:
A's constructor called
B's constructor called
B's constructor called
B's constructor called
A's constructor called
A's copy constructor called
A's copy operator= called
It is simple to understand that whenever the class instance (object) getting created associated constructor is getting called.
Now my question is that why in the first case the constructor of A is called only once , whereas in the second code its called twice.
You are creating second object directly in stack and constructor is getting called in later case, first one is the static and second one by creating object in stack by below statement.
A a ;
In first case, instead of constructor, copy constructor is getting called so thats why you are not getting the print statement second time.
A a = b1.getA();
So I'm just getting caught up in some nuisances of C++. Specifically, passing anonymous variables by reference for use in an initializer list for a class in C++. Consider the following code;
class A {
public:
int x;
A(int x=0) : x(x) {
std::cout <<"A: creatred\n";
}
~A() {
std::cout << "A: destroyed\n";
}
};
class B {
public:
A a;
B(const A& in) : a(in) {
std::cout <<"B: creatred\n";
}
~B() {
std::cout << "B: destroyed\n";
}
};
int main() {
B b(A(0));
std::cout << "END\n";
return 0;
}
outputs:
A: creatred
B: creatred
A: destroyed
END
B: destroyed
A: destroyed
I count 2 creations and 3 destructions. What's going on? Way I see it, I'm using an anonymous variable A(0) as input when creating b. Not sure what the order of things are now. A reference to the anonymous variable is created and used to copy (the copy constructor will be called in the initializer list, yes?) the member variable a. When is the anonymous variable destroyed? And in general, why am I seeing 2 constructors called and 3 destructors. Thanks.
You didn't override A's copy constructor to print a message...
Specifically, a(in) invokes it.
The missing constructor would be the copy constructor for A.
You copy construct A in the below line.
B(const A& in) : a(in)
A: destroyed
END
This is the temporary being destroyed, it is destroyed at the end of the line
B b(A(0));