Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C++ treat Class Objects like value types if initialized without the new operator?

Sample code:

MyItemType a;
MyItemType b;
a.someNumber = 5;
b = a;

cout << a.someNumber << endl;
cout << b.someNumber << endl;

b.someNumber = 10;

cout << a.someNumber << endl;
cout << b.someNumber << endl;

The output:

5
5
5
10

If a and b were reference types, the last 2 lines would have been 10 and 10 instead of 5 and 10 I guess.

Does this mean when you do a declaration like this:

AClassType anInstance;

it is treated like a value type?

------Here is MyItemType.h------------

#ifndef MYITEMTYPE_H
#define MYITEMTYPE_H

class MyItemType{

public:
    int someNumber;
    MyItemType();
};

MyItemType::MyItemType(){
}

#endif  /* MYITEMTYPE_H */
like image 237
Koray Tugay Avatar asked Nov 28 '22 08:11

Koray Tugay


2 Answers

Basically, yes (if you consider the C++ equivalent to mean the same as in Java).

AClassType anInstance; is an object, not a reference. MyItemType a and MyItemType b are different objects, they reside in different memory space, so obviously changes to one won't affect the other.

When you do a=b, you don't reference one object with the other, but, in this case, do a member-wise assignment. It's basically like saying

a.someNumber = b.someNumber;
like image 96
Luchian Grigore Avatar answered Dec 10 '22 12:12

Luchian Grigore


It is not treated like a value type, in fact it is.

While in Java object variables store references to objects, in C++ there is an important difference between an object and its reference. Assignment is by default really by value.

If you want a variable to be just a reference, you use either a reference or a pointer type, depending what you want to with it. These types are declared T* and T&.

To illustrate this a little more:

In Java, when you say MyClass obj, an object is created, but a reference/pointer is stored in the variable obj.

In C++, MyClass obj creates the object and will stored it in obj. If you want to work with references/pointers, you need to declare variables explicity as MyClass* objPointer or MyClass& objReference.

like image 33
Zane Avatar answered Dec 10 '22 10:12

Zane