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!
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!
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...
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;
#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;
}