If I have a user defined default constructor in my Test class, and what operations will done by using the following statement:
Test *test = new Test; //there is no () after new Test
First, does the user default constructor means "constructor without Parameters"?
for example:
class Test {
public:
Test() {
// do something here
}
}
so the new Test; means the complier will call the Test() constructor in class Test(); and perform the operations inside it, and allocate memory in heap for class Test object?
And what about the *test"? where is it ? in heap or stack? can anyone explain me?
And what about
Test test = new Test();//with () this time
what kind of constructor will be called in this case?
"Default constructor" means a constructor that can be called without parameters. It may have default parameters:
class Test {
public:
Test(int x = 42); // Still default constructor.
// Can be called as Test() and as Test(int);
};
The new operator will call operator new to allocate memory, and provided the allocation succeeds, then call one or more constructors. In this case it will call the default one to construct your object.
More than one constructor will be called if your object has a base class.
The Test* itself, test, will reside on the stack in this case.
Default constructor means the one which can be called without any parameters which includes constructors with parameters having all default values.
The statement Test *test = new Test allocates the memory for object of Test on heap and calls the default constructor for it.
Does the user default constructor means "constructor without Parameters"?
Yes, Default constructor means the constructor without any parameters. A constructor is a special & only member function for a class which has same name as the class.
The compiler generates a default constructor(constructor without any parameters) if your code needs one.
What does Test *test = new Test; do?
It allocates memory on the heap of size = size of class Test and calls the default constructor Test().
*And what about the test"? where is it ? in heap or stack? can anyone explain me?
*test is a pointer variable of the type Test on the stack which points to a dynamically allocated chunk of memory of the size of class Test on the Heap
A default constructor means a constructor that can be called without arguments. It is used to initialize the parameters of any object of a class, not necessarily pointers to objects of that class. So,
Test t;
would call the default constructor Test::Test(). Note that t is an object and not pointer to object. Some languages also have default constructors that are automatically generated when explicit constructors are not defined and over-ridden when constructors are defined.
The new operator in C++ allocates memory to the pointer from the heap and initializes it using the constructor.
HTH,
Sriram.
Related
I try to replicate C++ destructors and constructors in my c programming. That means for every object or struct there is an initialization function and a destruct function which frees all of the objects resources like so:
struct MyObject {
struct string a;
struct string b;
struct string c;
};
ConstructMyObject(struct MyObject *obj) {
ConstructString(&obj->a);
ConstructString(&obj->b);
ConstructString(&obj->c);
}
DestructMyObject(struct MyObject *obj) {
DestructString(&obj->a);
DestructString(&obj->b);
DestructString(&obj->c);
}
The destruct function is called at the end of every function scope just like in c++ only that i put it manually there. So now in DestructMyObject function I call the destructors of every struct string type because for the struct string object i would also have a destruct function written just like for the struct MyObject Object.
Example with my problem:
int main {
struct MyObject Object1;
ConstructMyObject(&Object1);
...
...
...
TransferOwnershipFunction(Object1.b); /*takes a struct string object as argument*/
...
...
...
DestructMyObject(&Object1);
return 0;
}
You see that i have transfered ownership of one Member of Object1 to another function but everything of Object1 will be destroyed by its destructor in the main function.
How do c++ destructors handle this kind of situation? I don't want that the destructor for struct string b is called at the end of main but it will be called because i call the destructor for MyObject. The function TransferOwnershipFunction(...) is now responsible for freeing the string object.
EDIT
Somebody knows how a rust compiler would resolve this issue? So in Rust would i need to clone the struct string object I'm passing to TransferOwnershipFunction or is there another way of doing it because cloning (or copying i guees) seems to be a very expensive operation.
From my point of view main() should be responsible for creating and deleting of Object1. And TransferOwnershipFunction() should work with a copy of Object1.b. In this case:
You need to create functions which work as analog of copy constructor and assignment operator (for C++03). Also move constructor and move assignment operator were added in C++11.
In C++03 copy constructor and assignment operator are generated implicitly if you don't declare them. By default they copy objects by member of class (not by bytes in memory) using copy constructor of each member (except simple types like int, double...). So you need to imitate of passing Object1.b by value with calling of copy constructor: in TransferOwnershipFunction create new object of type struct string, copy content of it by member. If struct string contains a raw pointer as member and you call malloc for this member in struct string's constructor and free in destructor than in copy constructor of struct string you need to call malloc than copy all content from passed variable. Don't forget to call destructor at the end of TransferOwnershipFunction.
According to RAII you need to call destructors in reverse order relation to order of creating objects (order of constructors).
Can any body explain why i am not able to create the object using new if it is overloaded and constructor is private.
class A
{
A();
A(A const &obj);
A& operator =(A const &obj);
public:
void * operator new(Size_t size)
{
void * p = malloc (size);
return p ;
}
};
int main ()
{
A * p = new A() /*gives compile time error, saying constructor
is private.But cant we access private function from class
public function . as operator new is public function of class.*/
return 0;
}
Possibly you are conflating a new-expression with operator new.
An operator new is an allocation function, with a confusing name. It should better have been called _alloc or some such.
A new-expression
calls the allocation function, passing any specified arguments.
if that succeeds, calls the class constuctor with specified arguments.
Here the relevant constructor must be accessible.
if that fails, cleans up by deallocating memory (in the case where the allocation function has user defined arguments, a corresponding user defined deallocation function is called with the originally specified custom allocation function arguments).
In short, a new-expression guarantees that if you have fulfilled your obligations, then you will either have an initialized object at hand, or an exception with no memory leak.
One way to not fulfill your obligations is to defined a custom allocation function with no custom deallocation function. Then in the last bullet point above you get no cleanup, and hence a memory leak. But other than that, a new-expression is almost like a database transaction, it guarantees all-or-nothing.
Constructor is called after operator new. As you can see, in operator new you are only using malloc to allocate raw memory. Afterwards, default constructor is called to initialize class members. So new A() calls both, operator new and constructor, constructor is private, so you cannot access it, and thus compiler won't allow it.
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).
From Thinking in C++
The first hidden argument to the constructor is the this pointer. this pointer holds the address of the caller object. In the case of constructor this pointer points towards an uninitialized block of memory. It is the job of the constructor to initialize this block of memory properly.
So, basically, the constructor is used to get a pointer to the object's space in RAM? Is that correct?
How does the default constructor initialize that memory? Does it get initialized to zero?
The role of the default constructor is the same as any other constructor: To initialize the object. The default constructor (or a constructor with only default arguments) sets member variables to a known state, like setting pointers to nullptr (or 0), etc.
Lets say we have this structure:
struct Foo
{
int a;
int* b;
// Default constructor
// Set `a` to `1`, and `b` to `nullptr`
Foo() : a(1), b(nullptr) {}
};
Now when you declare an instance of the Foo class, then you know what state the member variables will have. If there wasn't a constructor, a normal local variable instance of the Foo class would have undefined values for the a and b members.
If you don't provide a constructor at all, default or other, then the compiler will make a default constructor for you (one is needed, or you would not be able to create instances of the classes), but it will not do any initialization of members.
The hidden argument talked about, is the variable known as this, and it exists for all member functions which are not static.
So, basically, the constructor is used to get a pointer to the object's space in RAM? Is that correct?
No, the constructor is not used to get a pointer.
The purpose of the constructor is to initialize all member variables when an object of this class is created. It initializes the object in memory.
The default constructor is the constructor that can be called with no arguments.
When you implement a class, you can implement your own default constructor to make it do what you want it to do.
When you do not provide any constructor for your class, the compiler will provide a default constructor for this class, but it will not initialize the members.
Default constructors are significant because they are automatically invoked in certain circumstances:
When an object value is declared with no argument list, e.g. MyClass x;; or allocated dynamically with no argument list, e.g. new MyClass or new MyClass(); the default constructor is used to initialize the object
When an array of objects is declared, e.g. MyClass x[10]; or allocated dynamically, e.g. new MyClass [10]; the default constructor is used to initialize all the elements
When a derived class constructor does not explicitly call the base class constructor in its initializer list, the default constructor for the base class is called
When a class constructor does not explicitly call the constructor of one of its object-valued fields in its initializer list, the default constructor for the field's class is called
In the standard library, certain containers "fill in" values using the default constructor when the value is not given explicitly, e.g. vector<MyClass>(10); initializes the vector with 10 elements, which are filled with the default-constructed value of our type.
In the above circumstances, it is an error if the class does not have a default constructor.
No. The constructor is not used to get a pointer. The constructor receives this pointer.
The constructor is used to initialize the object's space in RAM.
The default constructor does what you want it to do! I mean your can write your own default constructor for your class. This default constructor can initialize the memory, or leave it uninitialized, as you choose.
In the same vein, the implicit default constructor will be written automatically by the compiler to initialize the object RAM space. It will take care of initializing the non-static member variables of your class that do have default constructors. For example, if your class has a non-static std::string as member variable, then std::string default constructor will be called to initialize this variable. All non-static member variables of POD types (int, char, pointers,...) will not be initialized.
No.
MyClass obj; // Default construct
MyClass* obj2 = new MyClass; // Also default construct
In the first one, space for obj is first allocated, typically in the stack. The second one is allocated on the heap. The addresses where they reside are the ones that are passed to the proper constructor in these case.
The first-argument-is-the-this-pointer situation does not only apply to the default constructor, as a hidden this pointer is passed to all non-static class methods as their first arguments[1].
Then you probably know the rest. The constructor sets-up and initializes the object's members and states and any other things that needs to be done.
[1]Have you observed some examples like this?
my_type obj;
func_that_calls_a_callback(std::bind(&my_type::method, &obj));
That demonstrates that the first parameter is a pointer to some object is bound to the first parameter of my_type::method. That becomes the this pointer which points, in this case, to obj.
So, basically, the constructor is used to get a pointer to the object's space in RAM? Is that correct?
No, that's just a consequence
How does the default constructor initialize that memory? Does it get initialized to zero?"
No: the default constructor is just a function. It does what what you define it to do.
It is normally designed to "initialize" the memory by assigning to the contained variables (the object member) a proper value or by calling in turn their own constructors.
Think to this:
class point
{
public:
int x,y; //< just two values
point() //< default constructor
{ x=0; y=0; } //< function body assigning values
};
or
class point
{
public:
int x,y; //< just two values
point() //< default constructor
:x(), y() //< member init-list explicitly calling contrutors
{} //< empty body
};
Note that, until you don't declare a variable of type point nothing will be executed.
int main()
{
point p; //< p created and point::point() called using p as *this
p.x=5; //< x member of p changed
return 0; //just exit main (jumps to the closing } )
} //< p destructor called here, using p as *this.
As per the "implicit default constructor", what it does is just:
call the bases implicit default constuctors
call the members implicit
default contructors.
For all class-based types, decaring a default ctor in fact replaces the implicit one, but -for "built-in types" (like int, char, float etc.)- the default explicit constructor -in fact- sets the value to zero, but the implicit one does nothing, thus letting the value uninitialized. (the implementations can use different techniques to come to this same result)
#include <cstdio>
struct A {
int a;
A() {
a = 2;
printf("Default\n");
}
A(int b_) {
a = 1;
if(b_ == 10) {
A();
}
}
};
int main(int argc, char **argv) {
A a(10);
printf("a=%d\n", a.a);
A b(11);
printf("b=%d\n", b.a);
return 0;
}
This prints:
Default
a=1
b=1
That is, it enters the Default constructor when b_ == 10, but not when it's not. But it doesn't change the value in a.a, even though it enters the Default constructor.
Why?
You aren't calling the constructor. You're just creating a temporary A then destroying it immediately. You can't call other constructors from a constructor in the current standard (C++03), and even in C++0x, you can only call other constructors from the initialisation list.
Most answers so far say that you're not calling a constructor. You're seeing the output of the constructor call. So just disregard those answers that are denying reality by over-simplifying.
The code snippet
if(b_ == 10) {
A();
}
creates and destroys a temporary object of class A.
As part of the creation the A default constructor is called to initialize the object.
The C++98 rules are designed to ensure that unless you use very low level functionality to impose your contrary will, every creation of an object of type T corresponds to exactly one T constructor call on that object. And vice versa, if you call a T constructor (which is another valid view of the above code) then, in C++98, you're creating a T object. You can call that the C++ constructor call guarantee: creation = constructor call.
The constructor call guarantee means, among other things, that a constructor call failure is an object creation failure: if a constructor fails, then you don't have an object.
Which simplifies things a lot.
For example, it says that if you do new A, and the A default constructor fails, then you don't have an object. So the memory that was allocated to hold that object, is automatically deallocated. And so that expression does not leak memory even if the object construction fails -- instead of an object, you just get an exception.
It's almost beautiful. :-)
A(); doesn't do what you think it does. (e.g. call the default constructor)
It creates a temporary object, which then is discarded.
A(); creates a new (temporary) instance of A, calling its default constructor.
You cannot call another constructor from a constructor.
If you have a lot of initializing to do, you could create a private method and call it in both constructors.
In this code:
if(b_ == 10) {
A();
}
You're putting a temporary A() on the stack, not calling the default constructor of A.
To do what you intend, you'll need to factor out the code in the default constructor into a helper function, then call that function from here and the default constructor.
With A() (in A(int b)), you are creating a new, different object.
Googlr says this: Can I call a constructor from another constructor (do constructor chaining) in C++?