views:

77

answers:

3

Suppose I have:

class Foo {
  ...
};
class Bar : public Foo {
  ...
};
Foo foo;
Bar bar;

Is there anyway to do the following:

foo_part_of_bar(bar) = foo;

foo = foo_part_of_bar(bar);

?

Thanks!

+1  A: 

Apparently, you mean that Bar is a descendant of Foo in class hierarchy...

In that case to do the first part can be done in two different ways

// foo_part_of_bar(bar) = foo;
bar.Foo::operator =(foo);
(Foo &) bar = foo; // or use a C++-style cast

(The latter might misbehave in the exotic case when the corresponding operator = is declared virtual and overriden in Bar. But that's, as I said, exotic.)

To do the second part you don't really need to make any special efforts

// foo = foo_part_of_bar(bar);
foo = bar;
// This is called slicing

Both have very limited use in some very special contexts. I wonder what you need it for...

AndreyT
+3  A: 

Assuming you meant class Bar : public Foo, the following should work.

For foo_part_of_bar(bar) = foo;

*(static_cast<Foo *>(&bar)) = foo;

For foo = foo_part_of_bar(bar);

foo = bar;
R Samuel Klatchko
Matthieu M.
This is assuming Foo has the default assignment operator / copy ctor. If both call virtual functions on the source then I don't think it's possible to copy the Foo part of bar to another Foo.
Steve Jessop
+1  A: 
#include <iostream>

struct Foo {
    Foo& operator=(const Foo&)
    {
        std::cout << "Foo::operator=\n";
        return *this;
    }
};
struct Bar : public Foo {
    Bar& operator=(const Bar&)
    {
        std::cout << "Bar::operator=\n";
        return *this;
    }
};

int main()
{
    Foo foo;
    Bar bar;

    Foo& foobar = bar;
    foobar = foo;

    foo = bar;

    return 0;
}
sbi