Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Assign child properties without effecting parent?

Assuming I have two classes a parent and a child class each with its own property(s)

class Parent
{
private:
    int m_nParentX;
public:
    Parent(int nX)
    {
        m_nParentX = nX;
    }
    int GetParentX()
    {
        return m_nParentX;
    }
};
class Child : public Parent
{
private:
    int m_nChildY;
public:
    Child(int nX, int nY) : Parent(nX)
    {
        m_nChildY = nY;
    }
    int GetChildY()
    {
        return m_nChildY;
    }
    
};

Then I have two instances of the Child class both with distinct values for each instance.

    Child a(10,20);
    Child b(30,40);

What I’d like to do is assign the properties of Child b to that of Child A; however I’d like to do this without effecting it’s parent properties

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If I do this

void Overwrite(Child* a, Child* b)
{
    *b = *a;
}
int main(int argc, const char * argv[])
{
    Child a(10,20);
    Child b(30,40);
    
    std::cout << a.GetParentX()<< ":" << a.GetChildY() << "\t" << b.GetParentX() << ":" << b.GetChildY() << std::endl;
    
    Overwrite(&a,&b);
    
    std::cout << a.GetParentX() << ":" << a.GetChildY() << "\t" << b.GetParentX() << ":" << b.GetChildY() << std::endl;
    return 0;
}

The output is

10:20   30:40
10:20   10:20

Which is not exactly what I want since I don’t want the parent’s X of Child b which is 30 to be replaced with Child a parent value of 10.
Essentially I’d like to output to be

10:20   30:40
10:20   30:20

Is it possible to do a quick assignment of classes without effecting parent properties?

>Solution :

Make a copy of the parent object first, Parent pCopyOfB = *b; then after you perform the assignment of the dereferenced pointers, cast b to its parent pointer and do a second assignment using the copy you saved earlier.

void Overwrite(Child* a, Child* b)
{
    Parent pCopyOfB = *b;
    *b = *a;
    Parent* pOfB = b;
    *pOfB = pCopyOfB;
}

This will restore the parent properties after overwriting the children properties. The output should be what you desired 10:20 30:20

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading