Destroying and creating an object

B

Bushido Hacks

I've come up with a good set of Matrix codes recently when I cam to a
road block. I would like to know if I should destroy an object to
create a new object with new dimmensions.

class Matrix{
public:
Matrix(int = 4, int = 4);
~Matrix();
Matrix &setDims(int, int);
Matrix &setRows(int);
Matrix &setCols(int);
Matrix &setVal(int,int,float);
Matrix &setInitVals();
Matrix &setIdentity();
Matrix &preMultiply(Matrix&);
int getRows() const;
int getCols() const;
float getVal(int,int) const;
const Matrix &operator=(const Matrix&);
private:
int rows, cols;
float** m;
};

Matrix::Matrix(int rows, int cols){
setDims(rows,cols);
m = new float*[getRows()];
for(int i = 0; i < getRows(); i++){
m = new float[getCols()];
};
setInitVals(); // this step is neccessary
};

Matrix::~Matrix(){
for(int i = getRows() - 1; i > -1; i--){
delete[] m;
};
delete[] m;
};

Matrix &Matrix::setDims(int rows,int
cols){setRows(rows);setCols(cols);return *this;};
Matrix &Matrix::setRows(int rows){this->rows = rows;return *this;};
Matrix &Matrix::setCols(int cols){this->cols = cols;return *this;};
Matrix &Matrix::setVal(int row, int col, float val){m[row][col] =
val;};
int Matrix::getRows() const {return rows;};
int Matrix::getCols() const {return cols;};
float Matrix::getVal(int row,int col) const {return m[row][col];};

Matrix &Matrix::setIdentity(){
for(int i = 0; i < this->getRows();i++){
for(int j = 0; j < this->getCols();j++){
this->setVal(i,j,static_cast<float>(i == j));
};
};
return *this;
};

Matrix &Matrix::preMultiply(Matrix &n){
// m[j] = m[k] * n[k][j]
try{
if(this->getCols() != n.getRows()) throw 1;
Matrix t(this->getRows(),n.getCols());
for(int i = 0; i < t.getRows(); i++){
for(int j = 0; j < t.getCols(); j++){
t.setVal(i,j,0.0);
for(int k = 0; k < t.getRows();k++){
t.setVal(i,j,t.getVal(i,j) + this->getVal(i,k) * n.getVal(k,j));
};
};
};
if(t.getRows() != n.getRows()) throw 2;
/* ========= AREA OF INTEREST ========== */
n = t; // Should I destroy object n so that a
// new n with t's dimmensions replaces it?
}
catch(int e){
cout << "Exception type " << e << " occured." << endl;
switch(e){
case 1:
case 2:
cout << "Insufficent matrix dimmesions." << endl;
break;
default:
cout << "Unknown exception type " << e << " occured." << endl;
};
}
catch(...){
cout << "Unknown exception occured." << endl;
};
};
const Matrix &Matrix::eek:perator=(const Matrix &rhs){
for(int i = 0; i < rhs.getRows();i++){
for(int j = 0; j < rhs.getCols();j++){
this->setVal(i,j,rhs.getVal(i,j));
};
};
return *this;
};
 
V

Victor Bazarov

Bushido said:
I've come up with a good set of Matrix codes recently when I cam to a
road block. I would like to know if I should destroy an object to
create a new object with new dimmensions.

[...]
Matrix &Matrix::preMultiply(Matrix &n){
// m[j] = m[k] * n[k][j]
try{
if(this->getCols() != n.getRows()) throw 1;


This is a definite abuse of exceptions. Throwing and catching in the same
function? Please... Couldn't you just write 'if -- else'?
Matrix t(this->getRows(),n.getCols());
for(int i = 0; i < t.getRows(); i++){
for(int j = 0; j < t.getCols(); j++){
t.setVal(i,j,0.0);
for(int k = 0; k < t.getRows();k++){
t.setVal(i,j,t.getVal(i,j) + this->getVal(i,k) * n.getVal(k,j));
};
};
};
if(t.getRows() != n.getRows()) throw 2;
/* ========= AREA OF INTEREST ========== */
n = t; // Should I destroy object n so that a
// new n with t's dimmensions replaces it?

Why destroy 'n'? Isn't '*this' the object that you should be changing?
What's 'preMultiply' do, changes its argument? That's bad design, IMO.
}
catch(int e){
[...]

V
 
H

Howard

Bushido Hacks said:
I've come up with a good set of Matrix codes recently when I cam to a
road block. I would like to know if I should destroy an object to
create a new object with new dimmensions.
Matrix &Matrix::preMultiply(Matrix &n){
// m[j] = m[k] * n[k][j]
try{
if(this->getCols() != n.getRows()) throw 1;
Matrix t(this->getRows(),n.getCols());
for(int i = 0; i < t.getRows(); i++){
for(int j = 0; j < t.getCols(); j++){
t.setVal(i,j,0.0);
for(int k = 0; k < t.getRows();k++){
t.setVal(i,j,t.getVal(i,j) + this->getVal(i,k) * n.getVal(k,j));
};
};
};
if(t.getRows() != n.getRows()) throw 2;
/* ========= AREA OF INTEREST ========== */
n = t; // Should I destroy object n so that a
// new n with t's dimmensions replaces it?
}


The parameter n is a reference to an existing object. How do you propose
you would destroy it and create a new one?

One solution might be to modify the operator= so that it deletes its
internal arrays, re-allocates them, then copies the data.

But I'm confused as to how this function is used, and what it is returning.
Why do you want to alter n, but return *this, which is not altered? Do you
really want to return t instead, and leave n alone? In that case, since t
is a local variable, you don't want to return a reference, but either a
pointer (and use new to create t, relying on code elsewhere to delete it) or
a copy (in which case you need a valid copy constructor.

-Howard
 
B

Bushido Hacks

Ah, but *this also has different parameters than t.

I personally, prefer this method of exception handling for two reasons:
Not too many people understand how to use exception handling, they'd
rather use assert. Assert requires an extra include file where as
try/throw/catch are of C++.

If/else is not ideal for exception handling. Throwing exceptions is
better.
 
B

Bushido Hacks

That missing "return *this" could be part of the problem.

*makes changes real quickly *

It didn't solve the problem but it was an important mistake.

Thanks for catching that.

Here's what I still have thus far.
This is the output as far as it will go:

Two matricies
[ 1 2 3 4 ]
[ 1 ]
[ 2 ]
[ 3 ]
[ 4 ]

Then an error message shows up.
The error I am receving durring runtime is:
The instruction at "0x0040164a" referenced memory at "0x00000000". The
memory could not be "read".
 
H

Howard

Bushido Hacks said:
Ah, but *this also has different parameters than t.

But why return *this at all, if it's never modified? And why attempt to
modify the parameter? Why not just return the new object you're creating?
I personally, prefer this method of exception handling for two reasons:
Not too many people understand how to use exception handling, they'd
rather use assert. Assert requires an extra include file where as
try/throw/catch are of C++.

If/else is not ideal for exception handling. Throwing exceptions is
better.

But how is throwing an exception better (than an if..else structure) if you
then go and catch them all in the very same function? (No one mentioned
asserts, by the way.) It really makes no sense to both throw and catch in
the same function. It introduces overhead that's not needed, and makes it
appear more complicated than it really is.

-Howard
 
H

Howard

Bushido Hacks said:
That missing "return *this" could be part of the problem.

*makes changes real quickly *

It didn't solve the problem but it was an important mistake.

Thanks for catching that.

Here's what I still have thus far.
This is the output as far as it will go:

Two matricies
[ 1 2 3 4 ]
[ 1 ]
[ 2 ]
[ 3 ]
[ 4 ]

Then an error message shows up.
The error I am receving durring runtime is:
The instruction at "0x0040164a" referenced memory at "0x00000000". The
memory could not be "read".

I misread what your code. It's hard to read in your post, with no blank
lines between the functions. I thought that the "return *this" was part of
that function. In any case, I am *not* suggesting you return *this, but
rather that you return t, since t is the new object you're creating.

Your error is lkely in that the operator= does not reallocate its arrays to
match the new size, as I suggested might be a problem.

Also, if you do return t as I suggest, then be sure you're either returning
a pointer (which you've new'd), or a copy, and if it's a copy, then add a
valid copy constructor which allocates the internal arrays.

-Howard
 
B

Bushido Hacks

Oh yeah, I forgot about that. I want to return a modifed 'n'.

As for the exception handling, that's how I've alway ben taught to use
it.
I wanted to use it as a quick escape when things seem doubtful. It's
just used as a safety precaution.

Keep in mind this is only a prototype.
 
B

Bushido Hacks

the operator= has nothing to do with it. I tried the function

for(int i = 0; i < t.getRows();i++){
for(int j = 0; j < t.getCols();j++){
n.setVal(i,j,t.getVal(i,­j));
};
};

and got the same problem.

I thought using the operater= would cut out alot of the clutter.
besides, it is much easier to copy an object typing n = t, than using
all that other stuff I just mentioned.
 
E

E. Robert Tisdale

Bushido said:
I've come up with a good set of Matrix codes recently

That's *your* opinion.
when I came to a road block.
I would like to know if I should destroy an object
to create a new object with new dimensions.

class Matrix {
private:
float** m;
int rows, cols; size_t rows, cols;
public:
Matrix(int = 4, int = 4);

Matrix(size_t = 0, size_t = 0);
~Matrix(void);

[snip]

This is a really *bad* design.
Take a look at
The C++ Scalar, Vector, Matrix and Tensor class Library

http://www.netwood.net/~edwin/svmtl/

Also, take a look at
The Object-Oriented Numerics Page

http://www.oonumerics.org/oon/
 
H

Howard

the operator= has nothing to do with it. I tried the function

for(int i = 0; i < t.getRows();i++){
for(int j = 0; j < t.getCols();j++){
n.setVal(i,j,t.getVal(i,-j));
};
};

and got the same problem.

I thought using the operater= would cut out alot of the clutter.
besides, it is much easier to copy an object typing n = t, than using
all that other stuff I just mentioned.

--------------------------------------------------------------------


But t doesn't have the same dimensions as n, does it? So whether that code
is inline or in the operator= function isn't relevant. It's attempting to
set the values for a matrix that's not the same size.

You need to delete the internal arrays in n, and reallocate them to the
correct size, as I've said repeatedly.


(But I still don't know why you don't return t. What is the return value
for, if not to hold the results?)


-Howard
 
R

Richard Herring

In message said:
int works just as well.
Please learn how to quote context when following up. It can be done,
even with the new Google interface. Without context, half your readers
have no idea what you're talking about.
 
B

Bushido Hacks

Richard said:
Please learn how to quote context when following up. It can be done,
even with the new Google interface. Without context, half your readers
have no idea what you're talking about.

*sighs* Can we atleast stay on the subject. Last time I checked, this
thread was in comp.lang.c++ not misc.education.language.english.

Can we stay on the subject and not critize me for my spelling, grammar,
style, usage, use of quotations, newsgroup edicate, use of exception
handling, programming style, and whatever other nit picky thing you
guys can find about my simple question?

I just want to know how to change object 'n', not hear about how I
should have used size_t, if/else statements, or any of that other
frivous crap.

The only relevant thing I have read in this thread is "You need to
delete the internal arrays in n, and reallocate them to the correct
size, as I've said repeatedly."

That's what I've been asking for help with in the first place!

I have no idea how to do this. Every time I attempt at doing so results
in crashing and the runtime error that I had metioned.
 
L

Lionel B

Bushido Hacks said:
*sighs* Can we atleast stay on the subject. Last time I checked, this
thread was in comp.lang.c++ not misc.education.language.english.

Hold on, did you understand what Richard said? If you reply with no context it is difficult to know what you are talking
about. I didn't understand your earlier post for that reason - who knows... I might have been able to help you...
Can we stay on the subject and not critize me for my spelling, grammar,
style, usage, use of quotations, newsgroup edicate,

The way this group works is as follows: you are asking people to help you out of the goodness of their hearts; they have
no obligation to help you. They are not being rewarded to help you. They are not going to help you if you make it
difficult for them to help you. They are not going to help you if you throw tantrums.
I just want to know how to change object 'n', not hear about how I
should have used size_t, if/else statements, or any of that other
frivous crap.

How do you know it's "frivous crap"? If you were smart enough to know what was crap and what wasn't, you wouldn't have
needed to post your crap code in the first place.
The only relevant thing I have read in this thread is "You need to
delete the internal arrays in n, and reallocate them to the correct
size, as I've said repeatedly."

That's what I've been asking for help with in the first place!

I have no idea how to do this. Every time I attempt at doing so results
in crashing and the runtime error that I had metioned.

Looking back on this thread, you have already received plenty of good advice which should have enabled you to fix your
problem by now.

Personally, I can't be bothered.
 
R

Richard Herring

In message said:
*sighs* Can we atleast stay on the subject. Last time I checked, this
thread was in comp.lang.c++ not misc.education.language.english.

Hey, you're the one asking for help here. The advice you receive will be
worth every penny you paid for it. We're under no obligation to respond
at all, and the more you antagonize the highly knowledgeable and
generally helpful people in this group, the less likely you are to get
help.
Can we stay on the subject and not critize me for my spelling, grammar,
style, usage, use of quotations,

I don't give a damn about any of that provided you can make yourself
understood. I simply DON'T KNOW WHAT YOU ARE TALKING ABOUT.
newsgroup edicate, use of exception
handling, programming style, and whatever other nit picky thing you
guys can find about my simple question?

I just want to know how to change object 'n',

And I for one haven't a clue what the hell object 'n' is, because you
hadn't quoted any context.
not hear about how I
should have used size_t, if/else statements, or any of that other
frivous crap.

The only relevant thing I have read in this thread is "You need to
delete the internal arrays in n, and reallocate them to the correct
size, as I've said repeatedly."

That's what I've been asking for help with in the first place!

I have no idea how to do this. Every time I attempt at doing so results
in crashing and the runtime error that I had metioned.

My advice would be to lose all the new[] and delete[] stuff and raw
pointers, and to use std::vector instead.
 
H

Howard

Bushido Hacks said:
*sighs* Can we atleast stay on the subject. Last time I checked, this
thread was in comp.lang.c++ not misc.education.language.english.

All you said was "int works just as well", and nobody has any idea what you
meant by that.
Can we stay on the subject and not critize me for my spelling, grammar,
style, usage, use of quotations, newsgroup edicate, use of exception
handling, programming style, and whatever other nit picky thing you
guys can find about my simple question?

I just want to know how to change object 'n', not hear about how I
should have used size_t, if/else statements, or any of that other
frivous crap.

It's all been good advice, hardly frivolous crap. It's up to you whether to
take the advice or not, obviously, but why insult people trying to help?
The only relevant thing I have read in this thread is "You need to
delete the internal arrays in n, and reallocate them to the correct
size, as I've said repeatedly."

That's what I've been asking for help with in the first place!

I have no idea how to do this. Every time I attempt at doing so results
in crashing and the runtime error that I had metioned.

You already have code to destroy the internal arrays in your destructor. If
you insist on keeping your current design, then just copy the code from the
destructor. Likewise, you already have code to create the arrays anew, in
your constructor. Copy the code from there.

If you still have problems, you could post the resulting code, and tell us
precisely where it still has problems. But honestly, since you don't seem
to want to follow our advice regarding what you're modifying and what you're
returning (which is where I think the true problem lies), and, since you've
now apparently offended some folks, you might not get the help you need any
more.

-Howard
 
B

Bushido Hacks

OK, I have figured out the problem.

The runtime error message was caused by the wrong variable.

Matrix &Matrix::preMultiply(Matrix &n){
try{
if(this->getCols() != n.getRows()) throw 1;
Matrix t(this->getRows(),n.getCols()); // m[j] = m[k] *
n[k][j]
for(int i = 0; i < t.getRows(); i++){
for(int j = 0; j < t.getCols(); j++){
t.setVal(i,j,0.0);
for(int k = 0; k < n.getRows();k++){
t.setVal(i,j,t.getVal(i,j) + this->getVal(i,k) * n.getVal(k,j));
};
};
};
n = t;
}
catch(int e){
cout << "Exception type " << e << "occured." << endl;
switch(e){
case 1:
cout << "Your arrays are insufficent for this matrix operation." <<
endl;
cout << "If you are multiplying arrays, the number of columns in"
<< endl;
cout << "the first array must be equivalent to the number of rows"
<< endl;
cout << "in the second array." << endl;
break;
default:
cout << "I don\'t know what an exception type " << e << " means."
<< endl;
cout << "Tell the guy who made this program about it." << endl;
break;
};
}
catch(...){
cout << "An unknown exception was detected." << endl;
};
return *this;
};

const Matrix &Matrix::eek:perator=(const Matrix &rhs){
if((this->getRows() != rhs.getRows()) || (this->getCols() !=
rhs.getCols())){
for(int i = getRows() - 1; i > -1; i--){
delete[] m;
};
delete[] m;
this->setDims(rhs.getRows(),rhs.getCols());
m = new float*[rhs.getRows()];
for(int i = 0; i < rhs.getRows(); i++){
m = new float[rhs.getCols()];
};
this->setInitVals();
};
for(int i = 0; i < rhs.getRows();i++){
for(int j = 0; j < rhs.getCols();j++){
this->setVal(i,j,rhs.getVal(i,j));
};
};
return *this;
};

This set of codes should allow the multiplication of matricies in an
output format similar to a TI-83's output.

With all of this aside, I appologize if I offened anyone.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top