Click here to Skip to main content
15,884,388 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi ,

I am new to c++, could you please help me with below code.

CObject	*m_pRetObj1; 
CObject *m_pRetObj2;
m_pRetObj2 = m_pRetObj1;


Requirement is m_pRetObj2 , should have all values of m_pRetObj1 in new address space. as of now, address space is same... i want address space to be different.

Please help me in resolving this issue.

What I have tried:

I have tried CObject *m_pRetObj2(m_pRetObj1). but address space is same.
Posted
Updated 1-Jun-20 7:18am

If you want different objects, then you need to create two different instances, and copy the data over.

At the moment, you don't create any instances, so your code won't work anyway: the pointer will either contain null values - and your app will crash when you try to use them - or they will contain random values - and your app will probably crash when you try to use them!

Think of it like cars: "Your car" is a variable which identifies the car you own (or are driving) - you can get out of a Ford, step into a Mercedes and "Your car" moves with it. Similarly, "My car" is a variable which holds the same info, but for me instead of you. Because we aren't married, "Your car" and "My car" are unlikely to hold the same vehicle - but it could happen.
Each car is an instance of the Vehicle class, and is independent - you create an instance (buy a Ford) and set the "Your car" variable to that new vehicle. When you sell it and buy a Mercedes, you pass the Ford instance to the new owner, and set "Your car" to the new Mercedes. The two vehicles are independent, so you don't expect to find the mobile you left in the glove box of the Ford in the Mercedes!

Objects in C++ are the same thing: in order to use them, you need to create an instance. Go back to your last couple of lecture notes, and read them again - you don;t seem to have understood what is going on well enough to move on yet.
You'll get it!
 
Share this answer
 
In a nutshell: your variables are ONLY pointer and NOT real objects. Imagine them as address values - and both addressing the same object in your code.

In your case a so called deep copy may help, when your CObject class has implemented it. Use the debugger or write a test to verify it.
C++
m_pRetObj2 = new CObject(m_pRetObj1);
You need to learn the language more in depth like with that Learn C++ tutorial.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900