Having a simple class:
class A {
public:
A() {}
void set(int value) { value_ = value; }
private:
int value_;
};
and its global instance:
A a;
Is it OK to call method set on a not yet constructed object a? That can happen when for example a.set(123) is called from a constructor of another global object in another translation unit.
Will the value in the object a set by calling a.set(123) remain when the non-parametric and empty constructor of A is later called for object a?
Is it ok to call method set on a not yet constructed object a?
No. You may not call member functions for an object that has not yet begun construction.
(Since the answer is no, your second question requires no answer.)
If you may need to access this global instance from multiple translation units during dynamic initialization, you can use the Meyers singleton technique:
A& global_a()
{
static A a;
return a;
}
a will be initialized when global_a() is first called. Note that in a multithreaded program you may need to concern yourself with synchronization of the initialization.
When you write
A a;
a is a constructed object now. In case A is a then A default constructor was already been called
If in 1) you mean it's ok to call set in the constructor, then yes, that's fine because it isn't a virtual method. You cannot call a virtual method in the constructor.
As for 2), what you're asking isn't really clear. The constructor is only called once (although there are ways around that sort of thing, but don't do them) and that is when the object is first created. You can't call the constructor on a a second time so the question doesn't really make sense.
Related
In C++ the "this" pointer points to the invoking object. However, when we call a constructor with a parameter, what does the "this" pointer point to?
For example, the following line calls the constructor:
TestManager myTest(device_name);
If I put a breakpoint inside the constructor function:
TestManager::TestManager(string device_name)
{
// bunch of code
}
What should I expect the "this" pointer pointing to?
The reason I am asking this question is that in my code, the "this" pointer is pointing to another object in my code that is not being called or used anywhere.
Thanks in advance.
this always points to the object. In the case of constructors or destructors, that means the object being constructed or destructed.
The reason I am asking this question is that in my code, the "this" pointer is pointing to another object in my code that is not being called or used anywhere.
Assuming your code is written somewhat sensibly, the object's only used after its construction has finished, so it makes sense that during the constructor, you haven't seen that particular value elsewhere yet.
'This' is pointing to an object that you are using currently. If you are writing methods, constructor, destructor, you can use 'this'. If you are writing friend functions, or static functions, you can't use 'this'.
this points to the instance of the current object being initialized. Once you reached the constructor, the necessary space for the object instance is already allocated and this points to it.
Just be careful when subclassing, and calling virtual/overriden methods from within a constructor:
Example:
class A {
A() {
this->work();
}
virtual void work() {
// ...
}
};
class B : public A {
B() {
// ...
}
void work() override {
// use some private members of B
}
};
In this case, working with private members from A from within A's constructor is fine. But since derived classes' members are initialized (and allocated!) after the base class, the private members of B are invalid until you reached B's constructor. So your program will most probably crash if you run into this situation.
Other than that, I cannot think of any problems with using this in the constructor of A.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
What methods are called when we create an object of a class in c++ or what exactly happens when we create an object of a class.
Without additional information, you should assume that one and only one member function of the class itself is called, the constructor.
class CheesePizza {
public:
CheesePizza() {}
};
CheesePizza barely; // will initialize by calling Foo::foo().
There are many cases in which additional functions might be called, for instance if you create a conversion scenario where a temporary object must be created, such as specifying a std::string argument and passing a const char* value.
class DIYPizza {
std::string m_toppings;
public:
DIYPizza(const std::string& toppings) : m_toppings(toppings) {}
};
DIYPizza dinner("all of the toppings");
This has to create a temporary std::string from the const char* argument, "all of the toppings". Then the DIYPizza::DIYPizza(std::string) operator can be passed this temporary (rvalue), and then subsequently we initialize m_str from it which invokes the std::string(const std::string&) copy constructor to initialize m_str.
What essentially gets done is:
// create a std::string object initialized with the c-string.
std::string rvalueString = std::string("all of the toppings");
// now we have a string to pass to DIYPizza's constructor.
DIYPizza dinner(rvalueString);
However - we're still only calling ONE member function of Foo at this point. The only way for more class members to be invoked is by calling them from whichever constructor is invoked.
class DinnerAtHome {
void orderPizza();
void drinkBeer();
void watchTV(); // I was going with something more brazen, but...
public:
DinnerAtHome() {
orderPizza();
drinkBeer();
watchTV();
drinkBeer();
// arrival of pizza is handled elsewhere.
}
};
Now when you construct a new DinnerAtHome, 5 member functions will be invoked: DinnerAtHome::DinnerAtHome() and the four member-function calls it makes.
Note: "new" is not a member function, it is a global operator.
IF the answer was "five" then either the interviewer was using a trick question or you missed some nuance of what was being asked.
Ok I try overkill answer since no once already selected an answer:
When you create an object the constructor is called, this also involves a call to underlying constructors of members objects, if the object inherits from another object you need also to call constructors of base classes
class Foo: public Bar{
std::vector<int> indices; //default constructor for indices is called
public:
Foo(int a):Bar(a){ //you have to call constructor of Bar here
//else compiling error will occur
}
};
Default constructor is called implicitly for objects that has it. When you create something with "new", first memory is allocated then object is constructed on top of that memory (placement new works in a similiar way, but the chunk of memory may be created explicity by the user elsewhere).
Note that in certain cases you don't know order of constructors calls:
CASE 1
Obj1* myobj= new Obj1 ( new Obj2, new Obj3( new Obj4) );
in this case you have no clues if Obj4 is created before or after Obj2 and if Obj3 is created before or after Obj2, simply the compiler will try to choose "an order" (that may vary depending on compiler and platform), also this is a highly unsafe code:
assume you get exception in Obj3 when Obj2 was already created, then Obj3 memory will never get deallocated (in that extreme case you may find usefull tools for those kinds of problems : Hypodermic / Infectorpp )
see also this answer
CASE 2
static/global variables may be initialized in different orders, and you have to rely on specific compiler functions to declare a initialization order
for GCC:
void f __attribute__((constructor (N)));
also note that "Constructor" is not a "method" like others, infact you cannot save constructor in a std::function nor bind it with std::bind. The only way to save a constructor is to wrap it with a factory method.
well that should be 5 "things" as you mentioned in the interview.
Lets assume your class is called CMyClass.
#include "MyClass.h"
/* GLOBAL objects */
static CMyClass g_obj("foo"); // static makes this object global to this file. you can use it
// anywhere in this file. the object resides in the data segment
// (not the heap or the stack). a string object is created prior
// to the constructor call.
int main(void)
{
....
if (theWorldEnds)
{
/* STACK */
CMyClass obj1; // this calls the constructor CMyClass(). It resides on the stack.
// this object will not exist beyond this "if" section
CMyClass obj2("MyName"); // if you have a constructor CMyClass(string&), the compiler
// constructs an object with the string "MyName" before it calls
// your constructor. so the functions called depend on which
// signature of the constructor is called.
/* HEAP */
CMyClass *obj3 = new CMyClass(); // the object resides on the heap. the pointer obj3
// doesn't exist beyond the scope of the "if" section,
// but the object does exist! if you lose the pointer,
// you'll end up with a memory leak. "new" will call
// functions to allocate memory.
}
}
If you are creating a class means you are calling constructor of that class. If constructor is not in your code than compiler will add the default constructor. YOu can override default constructor to perform some task on object creation.
For
Example:
If you are creating a object of type Person
Person* objPerson = new Person();
It means you are calling Person() method(constructor) of that class.
class Person {
public:
Person() {
// ...
}
};
When an object of a class is instantiated : memory required by the object of the class (depending on its data members) is allocated on the heap and a reference to that memory location is stored by the object name. This individual data members at this memory location on the heap may or may not be initialized depending on the constructor called.
When a new object is constructed, the constructor of the class is invoked to initialize non-static member variables of the class (if the class does not have any constructors, compiler assigns a an empty constructor for the class and invokes it). The constructor may invoke other functions (either library or user-defined functions), but that depends on the functions that programmer has invoked inside the constructor. Also, if the class is part of an inheritance hierarchy, appropriate constructor of base classes are called by compiler before the constructor of the class being instantiated (visit here for a brief explanation).
I wanted to run 1,000 iterations of a program, so set a counter for 1000 in main. I needed to reinitialize various variables after each iteration, and since the class constructor had all the initializations already written out - I decided to call that after each iteration, with the result of each iteration being stored in a variable in main.
However, when I called the constructor, it had no effect...it took me a while to figure out - but it didn't reinitialize anything!
I created a function exactly like the constructor - so the object would have its own version. When I called that, it reinitialized everything as I expected.
int main()
{
Class MyClass()
int counter = 0;
while ( counter < 1000 )
{ stuff happens }
Class(); // This is how I tried to call the constructor initially.
// After doing some reading here, I tried:
// Class::Class();
// - but that didn't work either
/* Later I used...
MyClass.function_like_my_constructor; // this worked perfectly
*/
}
...Could someone try to explain why what I did was wrong, or didn't work, or was silly or what have you? I mean - mentally, I just figured - crap, I can call this constructor and have all this stuff reinitialized. Are constructors (ideally) ONLY called when an object is created?
Your line Class(); does call the constructor of the class Class, but it calls it in order to create a "temporary object". Since you don't use that temporary object, the line has no useful effect.
Temporary objects (usually) disappear at the end of the expression in which they appear. They're useful for passing as function parameters, or initializing other objects. It's almost never useful to just create one in a statement alone. The language allows it as a valid expression, it's just that for most classes it doesn't do very much.
There is no way in C++ to call a constructor on an object which has already been constructed. The lifecycle of a C++ object is one construction, and one destruction. That's just how it works. If you want to reset an object during its life, you've done the right thing, which is to call a function to reset it. Depending on your class you might not need to write one - the default assignment operator might do exactly what you need. That's when a temporary can come in handy:
Class myObject;
// ... do some stuff to myObject ...
myObject = Class();
This updates myObject with the values from the freshly-constructed temporary. It's not necessarily the most efficient possible code, since it creates a temporary, then copies, then destroys the temporary, rather than just setting the fields to their initial values. But unless your class is huge, it's unlikely that doing all that 1000 times will take a noticeable amount of time.
Another option is just to use a brand new object for each iteration:
int main() {
int counter = 0;
while (counter < 1000) {
Class myObject;
// stuff happens, each iteration has a brand new object
}
}
Note that Class MyClass(); does not define an object of type Class, called MyClass, and construct it with no parameters. It declares a function called MyClass, which takes no parameters and which returns an object of type Class. Presumably in your real code, the constructor has one or more parameters.
What happens in that line reading...
Class ();
Is that you do in fact call the constructor - for a temporary object that is being constructed from scratch, and which is then immediately destructed since you're not doing anything with it. It's very much like casting to Class, which creates a value using a constructor call, except that in this case there's no value to cast so the default constructor is used.
It's possible that the compiler then optimises this temporary away, so there's no constructor at all - I'm not sure whether that's allowed or not.
If you want to re-initialise members, calling the constructor isn't the way to do it. Move all your initialisation code into another method and call that from your constructor, and when you want to re-initialise, instead.
Yes, this not typical usage. Create a function that resets your variables, and call the method whenever you need it.
You fell prey to a common misreading of c++. The new c++0x makes things a bit clearer.
The problem is constructions syntax looks like a function call.
void foo( int i ) { }
class Foo { };
Foo(10); // construct a temporary object of type foo
foo(10); // call function foo
Foo{10}; // construct a temporary object of type foo in c++0x syntax
I think the c++0x syntax is more clear.
You could do what you want with this syntax. But beware it is very advanced and you should not do it.
MyClass.~Class(); // destruct MyClass
new( &MyClass ) Class;
With such requirements, I generally write a clear() (public) method. I call it from constructor, destructor. User code can call it whenever it wants to.
class Foo
{
public:
Foo() { clear(); }
~Foo() { clear(); }
void clear(); // (re)initialize the private members
private:
// private members
};
To answer the question here, the clear() method may be called whenever it is required to re-initialize the class as it was just after the initial construction.
class Foo {
public:
Foo() { Foo(1)}
Foo(int x, int y = 0):i(x) {}
private:
int i;
}
Can anybody give me some reasonas about can I do this? If not why?
Because the language specification doesn't allow it. Just the way the language is. Very annoying if you're used to Java or other languages that allow it. However, you get used to it after a while. All languages have their quirks, this is just one of C++'s. I'm sure the writers of the specs have their reasons.
Best way around this I've found is to make a common initialization function and have both constructors call that.
Something like this:
class Foo {
public:
Foo() {initialize(1);}
Foo(int nX) { initialize(nx); }
private:
void initialize(int nx) { x=nx; }
int x;
};
It's a language design choice.
A constructor is a one time (per-object) operation that creates a new object in uninitialized memory. Only one constructor can be called for an object, once it has completed the object's lifetime begins and no other constructor can be called or resumed on that object.
At the other end of its life a destructor can only (validly) be called once per object and as soon as the destructor is entered the object's lifetime is over.
A prinicipal reason for this is to make explicit when an object destructor will be run and what state it can expect the object to be in.
If a class constructor completes successfully then it's destructor will be called, otherwise the object's lifetime has never begun and the destructor will not be called. This guarantee can be important when an object acquires resources in its constructor that need to be released in its destructor. If the resource acquisition fails then the constructor will usually be made to fail; if the destructor ran anyway it might attempt to release an resource that had never been successfully acquired.
If you allow constructors to call each other it may not be clear if a calling or a called constructor is responsible for the resource. For example, if the calling constructor fails after the called constructor returns, should the destructor run? The called constructor may have acquired something that needs releasing or perhaps that was what caused the calling construtor to fail and the destructor shouldn't be called because the resource handle was never valid.
For simplicity of the destruction rules it is simpler if each object is created by a single constructor and - if created successfully - destroyed by a single destructor.
Note that in C++11 a constructor will be able delegate to a different constructor, but there are limitations that don't really relax the principal of one construction per object. (The prinicipal constructor can forward to a target constructor, but if it does it must not name anything else (base classes or members) in its initializer list. These will be initialized by the target constructor, once the target constructor returns the body of the prinicipal constructor will complete (further initialization). It is not possible to re-construct any bases or members, although it allows you to share constructor code between constuctors.)
You cant do this. See section 10.3: http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.3. You can try to do it but doing so will construct a new temp object (not this) and be destroyed once control moves on.
What you can do however is to create a private function that initializes variables, one that your default constructor or a parameterized constructor can both call.
There is a really hideous hack I have seen used to call another ctor. It uses the placement new operation on the this pointer. erk
Like this:
Class::Class(int x) : x_(x) {}
Class::Class() {
new (this) Class(0);
}
Class::Class(const Class &other) : x_(other.x_) {}
Class& operator=(const Class &other) {
new (this) Class(other);
return *this;
}
Note that I am not recommending this, and I don't know what horrible effects it might have on C++ structures like virtual base classes, etc. But I expect that there are some.
Although as per standards vendors are free to implement data binding in their own ways, if we consider the most popular implementation: this pointer, we can see a reason why this can't be implemented.
Assume you have a class:
class A
{
public:
A(){}
A(int a){}
} ;
With the this pointer implementation, this class would look something like:
class A
{
public:
A(A *this){}
A(A *this,int a){}
} ;
Typically you would create objects like this:
A ob ;
Now when compiler sees this, it allocates memory for this and passes the address of this allocated memory block to the constructor of A which then constructs the object. It would try to do the same every time for each constructor called.
Now when you try calling a constructor within another constructor, instead of allocating new memory the compiler should pass the current objects this. Hence inconsistency!
Then another reason which i see is that even though you might want to call a constructor within another, u would still want a constructor to call default constructors for all the objects within the class. Now if one constructor were to call another, the default construction should happen for the first constructor and not for the subsequent one's. Implementing this behavior means that there would be several permutations which need to be handled. If not, then degraded performance as each constructor would default construct all the objects enclosed.
This is what i can think of as possible reasons for this behavior and do not have any standards to support.
I have a global member data object, defined in a header (for class MyMainObj) like this.
class MyMainObj
{
MyDataObj obj;
}
MyDataObj has a default constructor.
When is the constructor for MyDataObj called?
Is it called as part of the creation of MyMainObj?
MyDataObj in this case is not a member of MyMainObj, it's a local variable.
But, constructors for data members are called in your class's constructor. The default constructor for every member is called before execution reaches the first line in the constructor, unless you explicitly specify a constructor using an initializer list, in which case that constructor is called instead.
With that code, obj isn't a member of MyMainObj -- it's simply a local object inside that constructor. As such, it'll only be constructed when/if that constructor is invoked.
Concerning your code, you have a function with a variable inside. Upon entering the function, you will run to the line of code that declares the variable, and the constructor will be run then.
But you say "creation of MyMainObj". It's a function, it can only be called, not created.
This is all concerning the title question, "when are members constructed?" This would apply if MyMainObj was a class and not a function.
Your member objects are constructed in the order of which they appear in the class declaration. All objects are full constructed upon entering the constructor. (But this does not include the class itself!)
That is to say, by the time the class enters its constructor, all the members have finished their constructor.
Objects are destructed in reverse order, in the destructor (after the destructor is run).
In a pseudo-diagram:
MyClass
Member1
Member2
Member3
Construction:
Member1
Member2
Member3
MyClass
Destruction:
MyClass
Member3
Member2
Member1
You can manually call the members constructor using an initialization list:
class foo
{
public:
foo(void) : i(0) // construct i with 0.
{
}
int i;
};
There are various question on SO about initialization lists. Initialization list order, Copy-construction initialization list, and more.
Yes, the constructor would be called whenever a MyMainObj instance is created.
I'm a bit confused by the "global member" terminology - the way you've declared that object it would be a local variable inside the constructor. Am I missing something here?
Yes, as other stated the member will be created on the owner class creation, on construction (be it generated by the compiler or with a provided constructor).
The order of creation will be the same as how your members apear in the class declaration. For example :
class MyType
{
Thing a;
Thing b;
Thing d;
Thing c;
};
Whatever constructor is used, whatever the order in a initialization list, the members will be constructed in this order : a, b, d, c. Once it's all done, the constructor code will be executed (if it exists) and only then your whole object will be constructed.
Upon entering an object constructor, memory has already been allocated for it. Then the execution order is as follows:
Base class constructor, if any, as specified in the initialisation list; if not specified, the default constructor is used.
The constructors for the member data, as specified in the initalisation list (default if not specified), in the order they are declared in the class definition. The order in which they are specified in the initialisation list is irrelevant.
The constructor body.
In the example set in the question, the first thing that would be executed upon entering the default constructor of MyMainObj would be the default constructor of MyDataObj to construct the member data obj.
Given a class A:
class A {
MyDataObj obj;
}
If you don't write the constructor for A, the compiler will create one for you, which will create obj as part of constructing A (and destroy obj as part of destroying A.
If you do write a constructor for A, then obj will be created before your constructor runs, although you can reassign it:
class A {
MyDataObj obj;
public:
A() { } // obj created, but the value may or may not be predictable
}
class AA {
MyDataObj obj;
public:
AA()
{
obj = MyDataObj(5);
}
}
class AAA {
MyDataObj obj;
public:
AAA() : obj(5) { } // member initializer list, my preferred method
}
With the third option, the data objects are created before the member initializer list runs, and the values are assigned in the order they are declared in AAA, NOT the order they are listed in the member initializer list.
UPDATE: There is a difference between creation and initialization. Space for the data members (and the base classes, and the data members for the base classes) is always set aside -- which I would call "creation." However, that doesn't mean a useful value is stored in that memory. There are separate rules for whether an object is default initialized, which depend on the type of the data member (primitive, POD, non-POD) and, IIRC, the storage class of the main object (local, static, global). The easiest way to avoid surprises in this area is to simply make sure you explicitly initialize everything.