Click here to Skip to main content
15,396,239 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I've written a code in which I'm passing class as a parameter in fucntion the copy constructor for the class is written too in the body of the code

#include <iostream>
#include <string>
using namespace std;

class Move
{
private:
    int* age;
public:
    Move(int d);
    Move(const Move& source);
    ~Move();
    int get_value() { return *age; }
};

Move::Move(int d)
{
    age = new int;
    *age = d;
}
Move::Move(const Move& source)
{
    age = new int;
    *age = *source.age;
}

Move::~Move()
{
    delete age;
}

void display_element(Move P)
{
    cout << "the age of p is: " << P.get_value()<<endl;
}

int main()
{
    Move waleed(5);
    display_element(waleed);
    Move ahmed(waleed);
    display_element(ahmed);
    return 0;
}


I'm wondering where is the object of the (*age) member in the copy constructor body? every member should have a specific object in copy constructor I'm copying the age of waleed in newly *age member that will be passed later in the function so before passing it to the function where is the object decleration of this member

What I have tried:

I've tried to debug and see locals to see what's going behind I see a pointer variable called this is being created when the constructor is called maybe there is a relation between it and my question?
Posted
Updated 12-Sep-21 20:25pm

It seems to me there is no need to utilize a pointer to store age as shown below If you wish to utilize a pointer you should delete it before copying to it in the copy constructor else you will have memory leakage As to your question if I understand it You seem to be inquiring the location of the *age value It is of course stored at the memory address whose value is age

#include <iostream>
#include <string>
using namespace std;

class Move
{
private:
    int age;
public:
    Move(int d);
    Move(const Move& source);
    ~Move();
    int get_value() { return age; }
};

Move::Move(int d)
{
     age = d;
}
Move::Move(const Move& source)
{
    age = source.age;
}

Move::~Move()
{
}

void display_element(Move P)
{
    cout << "the age of p is: " << P.get_value()<<endl;
}

int main()
{
    Move waleed(5);
    display_element(waleed);
    Move ahmed(waleed);
    display_element(ahmed);
    return 0;
}
   
Quote:
I'm wondering where is the object of the (*age) member in the copy constructor body?

Quote:
I've tried to debug and see locals to see what's going behind I see a pointer variable called this is being created when the constructor is called maybe there is a relation between it and my question?
this is exactly what you are searching for (see this pointer - cppreference.com[^]).
   

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