C ++ How to assign / get a base class?

Suppose I have:

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

Is there any way to do the following:

 foo_part_of_bar(bar) = foo; foo = foo_part_of_bar(bar); 

?

Thanks!

+4
source share
4 answers

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; 
+4
source

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

In this case, the first part can be done in two ways.

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

(The latter may be mistaken in the exotic case, when the corresponding operator = declared virtual and is redefined in Bar . But this, as I said, is exotic.)

To complete the second part, you really do not need to make much effort.

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

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

+3
source
 #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; } 
+1
source

From here: C ++ Why can't I assign a base class to a child class

For foo_part_of_bar (bar) = foo;

 bar.Foo::operator=(foo); 

and for foo = foo_part_of_bar (bar);

 foo = bar; 
0
source

Source: https://habr.com/ru/post/1302647/


All Articles