This question already has answers here:
what is return type of new in c++?
(2 answers)
Closed 23 days ago.
if I have the following -
#include <iostream>
class object{
private:
public:
object();
object(some_item);
};
object a;
int main()
{
// why doesn't it let me do
a = new object(some_item);
// but lets me do
a = *new object(some_item);
}
I am trying to initialize a global object which will be initialized at runtime inside the main loop but not in the part where I defined it globally.
basically I want an object that is available globally and that can be initialized at runtime inside any function.
But I don't completely understand how the new/*new operator works.
operator new returns a pointer to a dynamically created object.
So, the type of this expression:
new object(some_item)
is the pointer type object *.
On the other hand, the variable a is declared as having the type object:
object a;
So, you are trying to assign a pointer of the type object * to an object of the type object:
a = new object(some_item);
and within the class object, there is no overloaded assignment operator= declared like this:
object & operator =( object * );
So, the compiler issues an error.
However, when the pointer expression is dereferenced, then you get an object reference of the type object& , and can assign it to the variable a:
a = *new object(some_item);
using the default generated copy assignment operator=.
Pay attention to that, in this case, you will have a memory leak, because the address of the dynamically allocated object will be lost.
If you want to have a dynamically allocated object, or an array of objects, then the variable a should have the pointer type object *:
object *a;
In this case, you may write in main():
a = new object(some_item);
And then you have to free it when you are done using it:
delete a;
Related
My question is influenced by Prof. Thomas Cormen's second comment on his Quora answer$.
He says that the constructor carries out the following three tasks:
Allocates memory for the object.
Initializes the instance variables of the object, e.g., by implicitly calling init in Python. (I also emphasize that the init method should initialize not some, but all of the instance variables.)
Returns a reference to (i.e., address of) the object.
However, the MSDN documentation for C++* says that it is the new operator that does that:
Allocates memory for an object or array of objects of type-name from the free store and returns a suitably typed, nonzero pointer to the object.
My question is, who is right? Or, is there something more to it, perhaps like the new operator always calls the constructor, as suggested by a comment on the post?
Thanks.
$ Unfortunately, Quora does not have the option to copy the link for a comment - I can only do so for the answer.
* Although I say C++, I think it is also true for other languages like Java and C# (I am not 100% sure though).
If you search for constructor on the linked MSDN page, it says this:
When new is used to allocate memory for a C++ class object, the object's constructor is called after the memory is allocated.
In other words, a constructor is called if one exists. If none exists, none is called.
When in doubt, read the specification. From en.cppreference.com
The new expression attempts to allocate storage and then attempts to
construct and initialize either a single unnamed object, or an unnamed
array of objects in the allocated storage. The new-expression returns
a prvalue pointer to the constructed object or, if an array of objects
was constructed, a pointer to the initial element of the array.
Constructor does not allocate memory.
new allocates memory, then calls the proper constructor.
Semi pseudo code here :
template <typename T>
T* new(Args... arguments_to_constructor_of_T_if_any)
{
void* mem = malloc(sizeof(T)); // Allocate memory
// Call constructor
// Compiler will produce machine code to construct object T over memory mem.
(mem) T(arguments_to_constructor_of_T_if_any);
return (T*)(mem);
}
An example :
class A
{
int a;
int b;
A(int a, int b) { this->a = a; this->b = b; };
}
int main()
{
A* a = new A(3, 4);
// After compiled, code above will look like :
void* mem = malloc(sizeof(A));
// Below is A(int, int) constructor
((T*) mem)-> a = 3;
((T*) mem)-> b = 4;
}
This question already has answers here:
Why should C++ programmers minimize use of 'new'?
(19 answers)
Closed 5 years ago.
Lets say we have this..
class MyClass
{
int value;
void addIntToObject(int num)
{
value = num;
}
}
MyClass *object = new MyClass();
object->addIntToObject(1);
object->addIntToObject(2);
Now let's say we do this again...
object = new MyClass();
By using new twice on the same object, does that mean we have deleted all data that was stored in object? can someone explain to me the exact workings of using new twice on the same object
Would this be an efficient way to free memory? (like using delete and delete[])
You didn't "do new twice on the same object". The new expression creates an object. By doing new twice you made two entirely separate objects.
The variable object is a pointer. It points to other objects. The = operator on a pointer means to change which object the pointer is pointing to.
So in your code there are two objects, and you change object (the pointer) to point to the second object. The first object still exists but nobody knows where it is, this is known as a memory leak.
The thing on left side of = is a pointer i.e to be simple it can contain adrress of some memory location/object instance
When you do new MyClass() -> each execution of this statement will produce a new instance/object/memory of MyClass
So when you do this first time,
MyClass *object1 = new MyClass();
// here object1 now holds the address of object
created by executing 'new MyClass()' suppose that address is 1
Now create a object again,
object1 = new MyClass();
//here object1 now holds the address of object
created by again executing 'new MyClass()' suppose that address is 2
In the end both objects remain in memory i.e 1 as well 2. So nothing is deleted.
The pointer(left side of =) was first pointing to object with adrress 1. Now, it pointing to object with adress 2.
I'm new to c++ and I'm having difficulties with constructor and classes. So, here is my header file:
#pragma once
#include <string>
using namespace std;
class test
{
private:
string name;
int number;
public:
test();
test(string i,int b);
};
This is cpp file:
#include "test.h"
#include <string>
using namespace std;
test::test(){}
test::test(string i,int b){
this->name=i;
this->number=b;
}
now, when I try to call
test t=new test("rrr",8);
I get:
1 IntelliSense: no suitable constructor exists to convert from "test *" to "test"
So, whats the thing with classes having * in their name ( for instance, classes without .cpp file don't have asterix, all others do)? And what do I do wrong?
I imagine you're coming from a Java/C# background. t is not a reference type here, it's a value type. new returns a pointer to an object. So you need any of the following:
test t = test("rrr", 8);
test t("rrr", 8);
test *t = new test("rrr", 8);
If you're not yet familiar with pointers, then definitely don't use the last one! But understanding the semantics of pointers is fairly critical; I recommend reading the relevant chapter(s) in your textbook...
So, whats the thing with classes having "*" in their name ( for instance, classes without .cpp file dont have asterix, all others do)???
You definitely need to learn about pointers. test * and test are two completely different types in C++. Here's two variables with those types:
test t;
test* p;
Here, t has type test, and p as type test*. We describe test* as "pointer to test".
You can often think of a pointer as being the memory address of an object. So in p, since it is a pointer, we could store the memory address of t, which is a test. To get the address of an object, we use the unary & operator, like so:
test t;
test* p = &t;
Note that t is a test object. You didn't need to say new test(). This is where C++ differs from other languages that you might have used, like C# and Java. In the above C++ code, t is a test object.
However, you can create objects with new test(), so what's the difference?
test t; creates a test object with automatic storage duration. This means it is destroyed at the end of its scope (often the function is being declared within).
new test() creates a test object with dynamic storage duration. This means you have to destroy the object manually, otherwise you'll have a memory leak. This expression returns a pointer and so you can initialise a pointer object with it:
test* p = new test();
So now let's look at your problem:
test t=new test("rrr",8);
We now know that new test("rrr", 8) returns a pointer to test (a test*). However, you're trying to assign it to a test object. You simply can't do this. One of them is an address and the other is a test. Hence the compiler says "no suitable constructor exists to convert from test * to test." Makes sense now, doesn't it?
Instead, you should prefer to use automatic storage duration. Only use new if you really really need to. So just do:
test t("rrr", 8);
test t=new test("rrr",8);
must be
// v
test* t=new test("rrr",8);
So, whats the thing with classes having "*" in their name
* is used to indicate a pointer, it's not in the name of the class. But it's a big topic, so you should do some reseach on this.
* is not part of the name, it's a modifier denoting, that the object is a pointer. A pointer is a variable holding address to some place in memory, where the actual object is stored. Some basics:
int i = 5;
int * pI = &i;
int * pI means, that you want to declare a pointer to place in memory, where an int is held. &i means, that you want to retrieve a pointer to variable. So now pI holds address in memory, where i is stored. Now you can dereference a pointer - get to value of the pointer:
int j = *pI;
Now you tell the compiler, that it should go to the address pointed to by pI and retreive its contents (since pI is a pointer to int, compiler will assume, that there's an int there).
Now, back to your example. new operator allocates memory dynamically for an object, so:
new test("rrr", 8);
results in allocating a memory for test class, calling its constructor with parameters "rrr" and 8 and returning a pointer to allocated memory. That's why you cannot assign it to test variable: new operator in this case returns a test *.
Try this code:
test * t = new test("rrr", 8);
T* t = new T;
// ^^^
When new is used in this object construction, it denotes the creation of a pointer. What are doing is dynamically allocating memory which I'm sure you didn't mean to do. The Rather, typical stack allocated object construction is done simply like this:
T t;
Even if you had intended on creating a pointer and allocating the memory, you did it the wrong way. A pointer is created with the * symbol, which you lacked in your code. Secondly, when you're done using the memory you created, you must remember to delete/delete[] your code. delete[] is used on dynamically allocated arrays. So this is how it would look for your pointer:
delete t;
You did not define t as a pointer:
test* t=new test("rrr",8);
Or just
test t = test("rrr",8);
First i am from JAVA.
In java we create class object like this.
Example example=new Example();
The Example class can have constructor or cannot have constructor.
I can use the same in c++ like this
Example* example=new Example();
Where constructor is compulsory.
From this tutorial http://www.cplusplus.com/doc/tutorial/classes/
I got that we can create object like this.
Example example;
Which do not require an constructor.
I have two questions.
What is the difference between both the way of creating class objects.
If I am creating object like Example example; how to use that in an singleton class.
like I usually do like this.
Sample* Singleton::get_sample() {
if (sample == NULL) {
sample = new Sample();
}
return sample;
}
Please guide me if I am wrong.
I can use the same in c++ like this [...] Where constructor is compulsory. From this tutorial I got that we can create object like this [...] Which do not require an constructor.
This is wrong. A constructor must exist in order to create an object. The constructor could be defined implicitly by the compiler under some conditions if you do not provide any, but eventually the constructor must be there if you want an object to be instantiated. In fact, the lifetime of an object is defined to begin when the constructor routine returns.
From Paragraph 3.8/1 of the C++11 Standard:
[...] The lifetime of an object of type T begins when:
— storage with the proper alignment and size for type T is obtained, and
— if the object has non-trivial initialization, its initialization is complete.
Therefore, a constructor must be present.
1) What is the difference between both the way of creating class objects.
When you instantiate object with automatic storage duration, like this (where X is some class):
X x;
You are creating an object which will be automatically destroyed when it goes out of scope. On the other hand, when you do:
X* x = new X();
You are creating an object dynamically and you are binding its address to a pointer. This way, the object you created will not be destroyed when your x pointer goes out of scope.
In Modern C++, this is regarded as a dubious programming practice: although pointers are important because they allow realizing reference semantics, raw pointers are bad because they could result in memory leaks (objects outliving all of their pointers and never getting destroyed) or in dangling pointers (pointers outliving the object they point to, potentially causing Undefined Behavior when dereferenced).
In fact, when creating an object with new, you always have to remember destroying it with delete:
delete x;
If you need reference semantics and are forced to use pointers, in C++11 you should consider using smart pointers instead:
std::shared_ptr<X> x = std::make_shared<X>();
Smart pointers take care of memory management issues, which is what gives you headache with raw pointers. Smart pointers are, in fact, almost the same as Java or C# object references. The "almost" is necessary because the programmer must take care of not introducing cyclic dependencies through owning smart pointers.
2) If i am creating object like Example example; how to use that in an singleton class.
You could do something like this (simplified code):
struct Example
{
static Example& instance()
{
static Example example;
return example;
}
private:
Example() { }
Example(Example const&) = delete;
Example(Example&&) = delete;
Example& operator = (Example const&) = delete;
Example& operator = (Example&&) = delete;
};
Example example;
This is a declaration of a variable named example of type Example. This will default-initialize the object which involves calling its default constructor. The object will have automatic storage duration which means that it will be destroyed when it goes out of scope.
Example* example;
This is a declaration of a variable named example which is a pointer to an Example. In this case, default-initialization leaves it uninitialized - the pointer is pointing nowhere in particular. There is no Example object here. The pointer object has automatic storage duration.
Example* example = new Example();
This is a declaration of a variable named example which is a pointer to an Example. This pointer object, as above, has automatic storage duration. It is then initialized with the result of new Example();. This new expression creates an Example object with dynamic storage duration and then returns a pointer to it. So the example pointer is now pointing to that dynamically allocated object. The Example object is value-initialized which will call a user-provided constructor if there is one or otherwise initialise all members to 0.
Example* example = new Example;
This is similar to the previous line. The difference is that the Example object is default-initialized, which will call the default constructor of Example (or leave it uninitialized if it is not of class type).
A dynamically allocated object must be deleted (probably with delete example;).
There is two ways to make/create object in c++.
First one is :
MyClass myclass; // if you don;t need to call rather than default constructor
MyClass myclass(12); // if you need to call constructor with parameters
Second one is :
MyClass *myclass = new MyClass();// if you don;t need to call rather than default constructor
MyClass *myclass = new MyClass(12);// if you need to call constructor with parameters
In c++ if you use new keyword, object will be stored in heap. it;s very useful if you are using this object long time of period and if you use first method, it will be stored in stack. it can be used only short time period. Notice : if you use new keyword, remember it will return pointer value. you should declare name with *. If you use second method, it doesn;t delete object in the heap. you must delete by yourself using delete keyword;
delete myclass;
1) What is the difference between both the way of creating class objects.
a) pointer
Example* example=new Example();
// you get a pointer, and when you finish it use, you have to delete it:
delete example;
b) Simple declaration
Example example;
you get a variable, not a pointer, and it will be destroyed out of scope it was declared.
2) Singleton C++
This SO question may helps you
First of all, both cases calls a constructor. If you write
Example *example = new Example();
then you are creating an object, call the constructor and retrieve a pointer to it.
If you write
Example example;
The only difference is that you are getting the object and not a pointer to it. The constructor called in this case is the same as above, the default (no argument) constructor.
As for the singleton question, you must simple invoke your static method by writing:
Example *e = Singleton::getExample();
1)What is the difference between both the way of creating class
objects.
First one is a pointer to a constructed object in heap (by new).
Second one is an object that implicitly constructed. (Default constructor)
2)If i am creating object like Example example; how to use that in an
singleton class.
It depends on your goals, easiest is put it as a member in class simply.
A sample of a singleton class which has an object from Example class:
class Sample
{
Example example;
public:
static inline Sample *getInstance()
{
if (!uniqeInstance)
{
uniqeInstance = new Sample;
}
return uniqeInstance;
}
private:
Sample();
virtual ~Sample();
Sample(const Sample&);
Sample &operator=(const Sample &);
static Sample *uniqeInstance;
};
Example example;
Here example is an object on the stack.
Example* example=new Example();
This could be broken into:
Example* example;
....
example=new Example();
Here the first statement creates a variable example which is a "pointer to Example". When the constructor is called, memory is allocated for it on the heap (dynamic allocation). It is the programmer's responsibility to free this memory when it is no longer needed. (C++ does not have garbage collection like java).
In the first case you are creating the object on the heap using new.
In the second case you are creating the object on the stack, so it will be disposed of when going out of scope.
In C++ you'll need to delete objects on the heapexplicitly using delete when you don't Need them anymore.
To call a static method from a class, do
Singleton* singleton = Singleton::get_sample();
in your main-function or wherever.
I'm relatively new to C++ and am having a hard trouble understanding the instantiation of object and pointers to objects.
Whats the difference between these two declaration in terms of memory and usage? :
MyClass obj1;
MyClass *obj2;
And also the specific problem I am having is that I have a class which has an unsigned short array where the last space of the array changes if I do this:
MyClass obj;
obj = MyClass("123");
MyClass has two constructors one which will take an int and as default will assign it to zero and splice it in parts of 3 digits or less. And another which will take a string representation of a number and do the same... hope that makes sense!
It works well if I declare it
MyClass obj = MyClass("123123123");
but not if I do it the other way. Why?
The difference:
MyClass obj1;
MyClass *obj2;
Here obj1 is an instance of MyClass.
While obj2 can potentially hold the address of an instance of MyClass.
Also obj1 will automatically be initialized by the constructors, while obj2 is not initialized by default (and thus points to random memory). Once initialized obj2 may take the special value NULL which indicates that it is not pointing at an object.
obj2 = &obj1;
Here we initialize obj2 to point at the address in memory of obj1. If you change any of the members of obj1 then you can see the changes by looking at them through obj2 (but because obj2 is a pointer you need to de-reference).
obj1.plop = 5;
std::cout << obj1.plop << "\n";
std::cout << obj2->plop << "\n"; Should print the same values.
The following is actually two different things:
MyClass obj;
obj = MyClass("123");
Line one initializes 'obj' with the default constructor.
Line two: creates a temporary object constructed with the string "123". Once this temporary object is created it is copied onto 'obj' using the assignment operator. If you did not define an assignment operator the compiler will have generated one for you. If your class contains pointers then the default version will probably not work correctly (in most other situations the default assignment operator should work fine).
This line probably works:
MyClass obj = MyClass("123123123");
Because the compiler has optimised this into:
MyClass obj("123123123");
When you say MyClass obj1; you create the object. MyClass * obj2; just saves space for the address of the object.
So MyClass obj1; does the following:
it sets up the name in the compiler symbol table
it allocates sizeof(MyClass) bytes of space — could be as big as you want
it runs the default ctor of MyClass, MyClass::MyClass() 9or a ctor that has all default arguments intead) putting the initialized object in the space it allocated
it remembers where that object is, associating it with the name 'obj1' in the symbol table.
while MyClass * obj2; instead
sets up the name obj2 in the symbol table
allocates space only for the address of a MyClass object, sizeof(MyClass*) — probably 4 or 8 bytes
doesn't run any constructor.
When you say MyClass obj; obj = MyClass("123123123") you
create and allocate a MyClass object for obj using the default ctor
create and allocate another MyClass object
assign that new MyClass object to replace the old one.
When you call
MyClass obj = MyClass("123123123");
You are actually creating two objects! The correct way is to call
MyClass obj("123123123");
In the first code, one actually creates the object of type MyClass so it consumes as much space as needed. the other one just defines a pointer, so you reserve as much space as you would need for an addresss on your system (typically 4 bytes, sometimes 8)
When you split your initialization into two lines, you are first creating MyClass with a default constructor, then creating a MyClass with a parameterized constructor, and then using the assignment operator to override the contents of the first with the contents of the second. This is wasteful. Because constructors can have side effects, the compiler would probably not optimize this for you.
In the third piece of code you provided, you are actually using a single constructor that takes a parameter. Not assignment takes place.
The difference between
MyClass obj1;
MyClass *obj2;
Is the first creates an object (size = size of the object), whereas the second only creates a pointer to an object (4 bytes on 32 bit systems) but not the actual object. In order to do that you'd need to do
MyClass* obj2 = new MyClass("123");
This would allocate 4 bytes for the pointer and the x bytes where x is the size of the object. If you manually "new" something like this, then you are responsible for manually destroying it later using "delete".
The MyClass obj1 will be "destroyed" when it goes out of scope.
Two things are affected by these declarations: the lifetime of the variable, and where the memory is allocated.
The pointer version MyClass* is declaring a variable that points at an instance of MyClass. It does not itself allocate it; the allocation from the 'free store' (which is always the same as the 'heap') occurs when you explicitly 'new' it, and is freed when you 'delete' it.
The following code works:
MyClass* test_works() {
MyClass* obj = new MyClass;
return obj;
}
The non-pointer version is allocating the memory in the context it is specified - the declaration might be at a global level, or on the stack in a function, or as a member of another object ('composition') - and it is automatically allocated and freed as it comes in and out of scope.
The following code, for example, will fail:
MyClass* test_crashes() {
MyClass obj;
return &obj;
}