Created
June 22, 2024 15:11
-
-
Save john9francis/2e1d0d13918a6084fe0906ee8d02c2d8 to your computer and use it in GitHub Desktop.
Copying a class in C++ creates a new instance of that class, but if any variables were declared with "new," those variables don't get copied, only their addresses do. Therefore the original instance and the copy essentially share the same variable.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// showing how copying an instance of a class | |
// doesn't copy the dynamically allocated variables, | |
// it simply copies over their address. So the new | |
// copy shares the old variable. | |
#include <iostream> | |
class Thing{ | |
public: | |
Thing(){ pInt = new int; } | |
int* pInt; | |
}; | |
int main(){ | |
Thing t1; | |
Thing t2 = t1; | |
std::cout << "Address to t1: " << &t1 << std::endl; | |
std::cout << "Address to t2: " << &t2 << std::endl; | |
std::cout << "Address to t1's int: " << t1.pInt << std::endl; | |
std::cout << "Address to t2's int: " << t2.pInt << std::endl; | |
} | |
// OUTPUT: | |
// Address to t1: 0x5052c8 | |
// Address to t2: 0x5052c0 | |
// Address to t1's int: 0x505388 | |
// Address to t2's int: 0x505388 | |
// note: t1 and t2 are different places in memory, | |
// but both of their pInt variables point to the | |
// same place in memory. | |
// so be careful copying variables in this way! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment