Delete object inside the class C++ [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
There is a part of my class, which I'm using to read data, byte by byte, until '\0' occur.
RESULT MyClass::readMethod(DataInputStream& s)
{
if ( condition = ok )
{
char tmp[32];
uint8 i = 0;
do {
tmp[i] = s.read_int8();
} while (tmp[i++] == '\0');
char *arr= new char[i];
for (uint8 j = 0; j < i; ++j)
{
arr[j] = tmp[j];
}
//delete[] arr;
}
}
I removed a lot of code for this post, since rest is less important.
My problem is, that I want to free up memory, but since I've got method:
I tried put it into destructor:
MyClass::~MyClass()
{
delete [] arr;
}
but compiler (I use Visual Studio 2010) underline it and says: "Error: identifier arr is undefined".
I can't use it in place where it is commented, because I've got following method:
char * getArr()
{
return arr;
}
But tbh, I don't know if it will work, I mean, if I can access arr outside the class. Im still learning C++ and OOP, and sometimes I'm confused.
Similiar problem is with constructor: how to initialize arr to be empty.

Your arr is local to readMethod. So the destructor does not know it. You have to declare arr as a class member.
class MyClass
{
private:
char* arr;
}
Then you can delete it in your destructor.

Related

how to accessing vectors in a loop [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am programming a Space Invaders clone and I am struggling at creating the bullets.
Whenever I click Space a bullet is supposed to be added to the vector and then I want to move them via a loop, but I dont understand how to create and handle it the proper way.
vector<Bullet> bullets(MAXBULLETS);
int bulletcounter = 0;
while (1) {
Sleep(10);
for (int i = 0; i < sizeof(bullets)-1; i++) {
bullets[i].Move(0, 1);
}
if (GetAsyncKeyState(VK_SPACE)) {
Bullet *bullet = new Bullet();
bullets[bulletcounter] = bullet; // Here is the error
bulletcounter++;
}
bullets is a vector that holds objects of type Bullet.
Bullet *bullet = new Bullet();
bullets[bulletcounter] = bullet; // Here is the error
Your bullet here is of type Bullet*. The two incompatible types get you the error.
To fix this, stop using a pointer and just instantiate an object:
Bullet bullet;
This creates a Bullet object using the parameterless constructor that you can then add to your bullets.
Do note though, that this currently does nothing since you initialize your vector giving it a predefined size bullets(MAXBULLETS), this already creates MAXBULLETS default constructed objects for you, ready to use:
Constructs the container with count default-inserted instances of T.
No copies are made.
Side note : stop using new altogether; this isn't Java or C#. If you need a dynamically allocated object then use a smart pointer. Most of the time, though, an object automatic-storage duration will do just fine.
My proposal
vector<Bullet> bullets;
while (1)
{
Sleep(10);
for (int i = 0; i < bullets.size(); i++)
{
bullets[i].Move(0, 1);
}
if (GetAsyncKeyState(VK_SPACE))
{
bullets.push_back(Bullet());
}

C++ destructor for class contains array of ptr to objects [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
For example if we have 2 classes
class A{
int size;
A** arr;
}
class B{
int size;
A** arr;
}
For A's constructor I wrote:
A::A(){
this->arr=new A* [20];
}
For B's constructor I wrote:
B:B(){
this->arr=new A* [20];
}
For A's destroctor I wrote:
A:~A(){
for(int i=0;i<this->size;i++){
delete this->arr[i];
}
delete [] this->arr;
}
For B's destructor I wrote:
B:~B(){
for(int i=0;i<this->size;i++){
delete this->arr[i];
}
delete [] this->arr;
}
Note that the size will grow as I put more obj into the arr.
Now my question is, while I am testing, there's nothing wrong, but after the main program returns, it gives me segfault?
Seems to me like a classic case of not implementing the copy constructor and passing an instance by copy. You should really read an article or two about memory management in c++, or use shared_ptr/unique_ptr.
You should initialize size in the constructor, too.
A::A(){
this->size=20;
this->arr=new A* [20];
}
same for B

dynamic allocation and polymorphism - c++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Need some insight on how to complete this last part of my Marina class. Any help would be greatly appreciated.
This is a big project I'm working on. I created a group of classes that are derived from a base class Boat using public inheritance. The Marina class represents the care of the boats in a Marina. The Marina class contains a fixed size array of pointers to Boat.
The function should place a new Boat into the Marina if there is room and each new boat must be dynamically allocated. The function should also ask the user what kind of boat they want and then add that kind to the next empty place in the array.
The error suggests that you forgot to include Boat.h (or anything defining class Boat) in your cpp file.
But anyway, code shown in question has some problems :
line _m[i] = NULL; is outside of the loop where i is declared and will raise an error - and I cannot imagine a reason to have it there ...
you create an uninitialized boat, and do not keep a pointer to it : how will you find and initialize it ?
You said that boats should be dynamically initialized, and that method _add_boat must be void. IMHO there are only two acceptable ways :
create the boat outside of the method and only use add_boat to put it in marina (throwing exception if marina if full) :
void Marina::_add_boat(Boat *boat)
{
for (unsigned i = 0; i < _num_boats; i++)
{
if (_m[i] == NULL)
_m[i] = boat;
return;
}
throw std::runtime_error("Marina full");
}
usage :
Boat b = new Boat();
marina._add_boat(b);
pass arguments to initialize boat
void Marina::_add_boat(int type, Owner& owner, ...) // arguments for Boat ctor
{
for (unsigned i = 0; i < _num_boats; i++)
{
if (_m[i] == NULL)
_m[i] = new Boat(type, owner, ...);
return;
}
throw std::runtime_error("Marina full");
}
Below is original answer left only because some interesting comments refere to it
Why not something like :
I assume you have an array of boats (Boat *) in the Marina of size _num_boats. An empty place is conventionnaly a NULL. It gives :
static const unsigned int _num_boats = 100; // the value you need or a constexpr
class Marina {
Boat * boats[_num_boats];
...
Boat * Marina::_add_boat() {
for (unsigned i=0; i<_num_boats; i++) {
if (boats[i] == NULL) {
boats[i] = new Boat();
return boats[i]; // returns dynamically created Boat if room in Marina
}
}
return NULL; // return NULL if Marina full
}
}
With this logic you set attributes of Boat after placing it in Marina ...

Having run time error with "delete[]" [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I was trying to program my own List class on C++.
Here is the code:
template <class T>
class List
{
private:
T *value, *valueHelper;
int valueSize;
public:
int size;
List()
{
valueSize = 2;
value = new T[valueSize];
size = 0;
}
void Add(T val)
{
size++;
if (size > valueSize)
{
valueSize *= 2;
valueHelper = new T[valueSize];
memcpy(valueHelper, value, sizeof(T) * (size - 1));
delete[](value);
value = valueHelper;
}
value[size - 1] = val;
}
void Clear()
{
delete[](value);
size = 0;
valueSize = 2;
value = new T[valueSize];
}
T & operator[](int P)
{
return value[P];
}
};
The problem appered when I used a class variable on this List Class.
When I do Clear to delete some memory, there are a run time error appers.
I have trying to check what cause this problem and I have find out that this line on the function Clear() is the error line:
delete[](value);
I can not understand, why?
I'm just guessing here, but it could be likely it is because you will have copies made of the List instance, for example by returning it from a function or passing it as a non-reference argument to a function.
Copying of objects are implemented by the default copy-constructor generated by the compiler, but it only does shallow copying, meaning it will copy the pointers but not what they point to. So then you will have two copies with pointers pointing to the same memory, and when one object deletes that memory the others pointer will be invalid.
You also have a memory leak in that you don't have a destructor, so when an instance goes out of scope then you loose the allocated memory forever.
You should also read about the rule of three.

Using 2d array in a class [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I'm having a few problems.
1) It says declaration of 'matrix' as 2d array must have bounds (**mPoint in header file). Why? I want it to be dynamic, how can I fix it?
2) Another problem is "mPoint" isn't declared in this scope, in (Square_Matrix::Set_Size) in the .cpp file.
3) Lastly it says the definition in the destructor (Square_Matrix::~Square_Matrix) is implicitly declared.
Nothing in my c++ book seems to answer my questions.
//header file
#include <iostream>
using namespace std;
class Square_Matrix
{
public:
int **mPoint;
int N;
Square_Matrix();
~Square_Matrix();
void Set_Size (int new_size);
};
//.cpp file
#include <iostream>
using namespace std;
#include "Square_Matrix.h"
Square_Matrix::Square_Matrix()
{
mPoint = new int*[0];
mPoint[0] = new int[0];
N = 0;
}
Square_Matrix::~Square_Matrix() //destructor
{
for (int i = 0; i < N; i++){
delete [] mPoint[i];
}
delete [] mPoint;
}
void Square_Matrix::Set_Size (int new_size)
{
for (int i = 0; i < N; i++){ //deallocates memory if there's already a matrix
delete [] mPoint[i];
}
delete [] mPoint;
N = new_size;
mPoint = new int*[new_size]; //create dynamic 2d array of size new_size
for (int i = 0; i < new_size; i++){
mPoint[i] = new int[new_size];
}
}
You did not declare the destructor in your class definition. So the compiler implicitly declared it. However then you define the destructor explicitly yourself. You may not do that.
In the constructor you did not initialize mPoint. So your code in for example function Set_Size has undefined behaviour.
Square_Matrix::Square_Matrix()
{
mPoint = new int*[0];
mPoint[0] = new int[0];
N = 0;
}
You do not want to do that, and it is not valid. Just set the value of mPoint to nullptr. You cannot allocate an array of size 0.
Square_Matrix::Square_Matrix() : mPoint(nullptr), N(0)
{
}