Assigning Objects in C ++

To contextualize my question, I use the Matrix class with the following definitions:

Matrix(unsigned int, unsigned int); // matrix of the given dimension full of zeroes
Matrix(Matrix*); // creates a new matrix from another one
int &operator()(int, int);  // used to access the matrix
int **matrix; // the matrix

Now take these two code snippets:

First of all:

Matrix test(4,4);
Matrix ptr = test;
ptr(0,0) = 95;

Secondly:

Matrix test(4,4);
Matrix *ptr = &test;
(*ptr)(0,0) = 95;

Both codes have the same effect, the element at position (0,0) gets 95 (the first fragment is very similar to Java, the reason I asked this question). The question is, do both methods correctly assign an object?

+4
source share
4 answers

This is a bit complicated.

Consider this simple class:

class Thing1
{
public:
  int n;
}

Now we will try the first experiment:

Thing1 A;
A.n = 5;

Thing1 B = A;
B.n = 7;

cout << A.n << " " << B.n << endl;

The result is "5 7". Aand B- two separate independent entities. Changing one does not change the other.

:

Thing1 *p = &A;
p->n = 9;

cout << A.n << " " << p->n << endl;

: "9 9"; p A, A.n p->n - .

:

class Thing2
{
public:
  int *p;
};

...
Thing2 A;
A.p = new int(2);

Thing2 B = A;
*(B.p) = 4;

cout << *(A.p) << " " << *(B.p) << endl;

"4 4". B = A , , A B , int. . , (.. ), , , , Matrix , - . .

EDIT: @AlisherKassymov, , Thing A=B; , . , . ( , , , (. 3). , , .)

+19

.

Matrix test, COPIED Matrix ptr. ptr, , Matrix test.

Matrix test Matrix *ptr. test. (*ptr), test.

Java

java ( int ). , . .

+4

test ptr. ptr test

. , ptr , test, , ptr(0,0) = 95; test(0, 0).

, , ptr test, ptr . , , test(0, 0).

, :

#include <iostream>
class Test{
public:
    int i;
};

int main(){
    Test c;
    c.i = 1;

    Test d = c;
    d.i = 2;
    std::cout << "Value: " << c.i << "\n";

    Test* e = &c;
    (*e).i = 2;
    std::cout << "Pointer: " << c.i << "\n";
}

, (), , , , , .

+2

Java ++

Matrix test(4,4);
Matrix &ptr = test;
ptr(0,0) = 95;

, , .. test.

, . , Matrix , ( Matrix). Matrix (.. , ), . .

In your comments, you mentioned that the first code will also change the source object. This immediately means that your class actually implements shallow copy logic. And it looks like this is not an intentional part of your design. Obviously, you forgot to follow rule three when you implemented your class Matrix.

+1
source

All Articles