4

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!

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
anon
  • 41,035
  • 53
  • 197
  • 293

5 Answers5

4

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...

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
4

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
  • 74,869
  • 16
  • 134
  • 187
  • 1
    Why not `static_cast(bar)` ? – Matthieu M. Feb 28 '10 at 13:00
  • 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 Feb 28 '10 at 17:42
  • 1
    This answer ignores that the fields of `Bar` may be laid out in the padding of `Foo`. I don't think there's a safe way to do what the OP wants. – Tavian Barnes Jul 14 '18 at 15:36
1
#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
  • 219,715
  • 46
  • 258
  • 445
0

Take a reference to the base class and then you can do anything you want with it, not just assign to it.

    class Base {
        Base& operator=(const Base& other);
    };

    Base meow();

    class Derived : public Base {
        void woof()
        {
            Base& baseRef = *this;
            baseRef = meow();
        }
    };
Bill Chapman
  • 71
  • 1
  • 3
0

From here: C++ How come I can't 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;
Community
  • 1
  • 1