I have the following class declaration -
class class_name{
-
public:
-
class_name(); // Constructor
-
-
// Member functions
-
void function_1();
-
void function_2(double *mat);
-
void function_3();
-
-
void function_2_re_def(double *mat);
-
void function_3_re_def();
-
-
public:
-
int rows;
-
int cols;
-
-
double *v1;
-
double *v2;
-
};
-
The member functions, function_1 and function_2, perform the same task. They store some computed data in the array. I define function_1 as follows -
void class_name::function_1()
-
{
-
v1=new(double[(rows+1)*(cols+1)]);
-
-
double some_number;
-
-
for(int i=1;i<=rows;i++){
-
for(int j=1;j<=cols;j++){
-
*(v1+i*(cols+1)+j)=some_number;
-
}
-
}
-
}
-
I define function_2 as -
void class_name::function_2(double *mat)
-
{
-
mat=new(double[(rows+1)*(cols+1)]);
-
-
double some_number;
-
-
for(int i=1;i<=rows;i++){
-
for(int j=1;j<=cols;j++){
-
*(mat+i*(cols+1)+j)=some_number;
-
}
-
}
-
}
-
The only difference is that I want to pass an array to the function that does the same task instead of being limited as I am in function_1 which will only allow the operation to be performed on a single array. I want to be able to call function_1 or function_2 inside another function to do something else with the computed data. If I use function_1 inside this other function, called function_3, no problems arise. -
void class_name::function_3()
-
{
-
// perform the computation,
-
function_1();
-
-
// The data in v1 can be accessed inside this function
-
-
// Print the data to screen
-
for(int i=1;i<=rows;i++){
-
for(int j=1;j<=cols;j++)
-
cout<<*(v1+i*(cols+1)+j)<<" ";
-
cout<<endl;
-
}
-
}
-
However, I cannot get this to work if I use function_2, i.e. if I define function_3 as -
void class_name::function_3()
-
{
-
// perform the computation,
-
function_2(v2);
-
-
// The data in v2 cannot be accessed inside this function
-
-
// Print the data to screen fails, program crashes
-
for(int i=1;i<=rows;i++){
-
for(int j=1;j<=cols;j++)
-
cout<<*(v2+i*(cols+1)+j)<<" ";
-
cout<<endl;
-
}
-
}
-
What is more infuriating is that if I redefine function 2 by removing the call to new -
void class_name::function_2_re_def(double *mat)
-
{
-
double some_number;
-
-
for(int i=1;i<=rows;i++){
-
for(int j=1;j<=cols;j++){
-
*(mat+i*(cols+1)+j)=some_number;
-
}
-
}
-
}
-
and redefine function_3 as -
void class_name::function_3_re_def()
-
{
-
// perform the computation,
-
v2=new(double[(rows+1)*(cols+1)]);
-
function_2(v2);
-
-
// The data in v2 can now be accessed inside this function
-
-
// Print the data to screen
-
for(int i=1;i<=rows;i++){
-
for(int j=1;j<=cols;j++)
-
cout<<*(v2+i*(cols+1)+j)<<" ";
-
cout<<endl;
-
}
-
}
-
The program doesn't crash. I would like to know why the first version of function_3 with the call to function_2 crashes when called and why the second version, function_3_re_d ef with the dynamic memory allocation before the call to function_2_re_d ef, doesn't.
Is there a scope issue that means that you must know the size of an array before passing arrays into class member functions?
Thanks for your help.
5 1893
This code: - void class_name::function_2(double *mat)
-
{
-
mat=new(double[(rows+1)*(cols+1)]);
-
etc...
doesn't do what you think.
mat is a local variable. It dies when the function completes. That is, mat is a copy of the original pointer.
Now if you need to change the address inside the original pointer and have that change visible in other functions, then you will need to pass the address of the original pointer: - void class_name::function_2(double **mat)
-
{
-
*mat=new(double[(rows+1)*(cols+1)]);
Oralloy 988
Recognized Expert Contributor
At the risk of being cheeky, how about passing as a reference to a pointer? -
void class_name::function_2(double *&mat)
-
{
-
mat = new double[(rows+1)*(cols+1)]
Then you can have happily confusing code that transparently assigns the outer pointer value.
BTW, this sort of memory management is interesting, but I would think that STL vectors are a much better choice in most instances.
You may pass a reference to a pointer.
What you save is making the copy of the pointer. However, underneath, the compiler implements a reference by using a pointer. That means you save nothing using a reference to a pointer.
What you should be using is a handle. Once you have allocated memory and pass that pointer around, you can't tell when it's safe to delete the allocation. It would only be safe if the pointer was the last copy in the program.
To keep track of the number of copies of the pointer you would need to implement reference counting.
You might read the C/C++ Insights article on using handle classes.
Oralloy 988
Recognized Expert Contributor
Yep.
I'm really unsure of what emaghero is trying to achieve.
If he wants reference counted dynamic arrays, he'll need to implement envelopes and include a reference count in the core object. Not difficult, actually, just tedious. @emaghero - what is it you actully are trying to achieve? Sign in to post your reply or Sign up for a free account.
Similar topics |
by: qazmlp |
last post by:
Does static member function of a class have 'extern "C" linkage ?
And what about non-static member functions ?
|
by: Randy Yates |
last post by:
Hi,
Is there a way to write a class member function that does not
require an instantiation of the object to be invoked? For
example,
class MYCLASS
{
bool CheckIfMYCLASS(string &teststring);
}
|
by: Srini |
last post by:
Hello,
Rules for inline functions say that they have to be defined in the same
compilation unit as their declarations. For class member functions this
means that the inline member functions must be defined either within
the class or within the same header file.
But its generally a good programming practice to have the declarations
and definitions in seperate files. This would make the future
maintenance of the code easier.
|
by: lovecreatesbeauty |
last post by:
Predefined class member functions and inheritance
How many member functions on earth can be provided (predefined) by
standard-compliant compilers?
Scott Meyers says that there are 6: (1)default constructor, (2)copy
constructor, (3)destructor, (4)assignment operator, (5)address-of
operator (non-const), (6)address-of operator (const), in `Effective
|
by: tricard |
last post by:
Good day all,
I have created a two dimensional array (matrix for my purposes) whose
size is dynamically allocated. (i.e. rowSize and colSize are both taken
as input, then malloc() is used to dynamically allocate the required
memory). After the matrix is returned to main I want to pass it to a
function, printMatrix() and have it displayed on screen. However, I do
not want to send the rowSize and colSize arguments; instead I want to
have...
| |
by: cweisbrod |
last post by:
Hi All,
I realize I may be posting to the wrong group, but I can't help but
think my problem is more related to C++ than Microsoft's particular C++
compiler.
I've been migrating a large project from CodeWarrior to Visual Studio
and I'm having some difficulty with the Microsoft compiler.
Here's the basic problem with simplified code:
|
by: SneakyElf |
last post by:
hi all, im super new with c++ (and no background in programming
whatsoever!)
i have a task to make functions to calculate total profit and the
average number of things sold. data is read from a file. my problem is
with functions, namely setting up parameters and later calling
functions in the main().
here are the two functions (?) that i wrote so far, one is supposed to
get total profit and the other calculate average
|
by: Andy Terrel |
last post by:
Okay does anyone know how to decorate class member functions?
The following code gives me an error:
Traceback (most recent call last):
File "decorators2.py", line 33, in <module>
s.update()
File "decorators2.py", line 13, in __call__
retval = self.fn.__call__(*args,**kws)
TypeError: update() takes exactly 1 argument (0 given)
|
by: Wynner |
last post by:
I'm an old Delphi programmer getting into the C++ world, and trying to wrap my head around this problem.
I have multiple classes derived from a generic class that passes one of it's functions as a parameter to another function. The code is very complex, so I've written this abridged version of what I am trying to do.
// genClass.h
#ifndef genClassH
#define genClassH
#include <Classes.hpp>
|
by: jthep |
last post by:
Hi I'm trying to write a JNI for a linkedlist class I wrote in C++. Basically I have a header file with the class definition and a C++ file with the definition of the class member functions.
I have a record file llist.h
class llist
{
private:
record *start;
char filename;
int readfile();
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |