Hello
I'm not new to C++ programming, but I have a question for you guys and gals :) So the code below compiles fine (due to that ugly workaround in main func), but that makes d_copy.field2 unitialized (0xCC bytes in MSVC). How would you change the code to make d equal to d_copy? You can't change the type of the global variable and you must use it to copy d. However, you can use pointers, references and whatever pleases you. I guess set and get functions are optional, but I'd love to see them too. Is that possible in C++? If not, please let me know! ;)

class CBase
{
public:
    CBase() : field1(0) {}
    ~CBase() {}

    int field1;
};

class CDerived : 
    public CBase
{
public:
    CDerived() : field2(0) {}
    ~CDerived() {}

    int field2;
};

CBase b;

void func_set(CBase *pb)
{
    b = *pb;
}

CBase func_get()
{
    return b;
}

int main()
{
    CDerived d;
    CDerived d_copy;

    d.field1 = 321;
    d.field2 = 123;

    func_set(&d);
    d_copy = *(CDerived*)(&func_get());

    return 0;
}

If the question is unclear to you, please let me know.

If the question is unclear to you, please let me know.

The point of this exercise is unclear to me. Is it just random homework from a teacher who thinks trivia will somehow make you a better programmer? Or do you have an actual real world need?

Change line 24 to b.field1 = (*pb).field1; . It then worked for me. And what is the motive of this exercise ?

I need it for my own project. This isnt a homework. Basically I want to have a class that stores the base class object and use it with derived objects in the manner Ive shown in the example. Ive already solved the problem with templates but I was wondering if you could do it that way. Ill provide more info later if necessary.

You probolly can get away with changing line 24 to

&b = pb;

That explains why d_copy.field2 is uninitialized. I was already aware of that, but thanks for pointing that out. So a template class is the only reasonable way to solve this problem? If it is so, then I guess this thread can be closed. I'll wait a little longer then I'll mark this question as solved.