1

Say I have a base class A and a derived class B that adds some extra members. Now I'd like to have a setter function for class B that acceses it's own members directly but assigns the derived members in batch using a temporary A object. Here's some example code:

class A
{
public:
    int x;
    int y;
    A(int arg1, int arg2) 
        : x(arg1), y(arg2) {}
};

class B : public A
{
public:
    int z;
    B(int arg1, int arg2, int arg3) 
        : A(arg1, arg2), z(arg3) {}
    void setB(int arg1, int arg2, int arg3) {
        /*something here*/ = A(arg1, arg2);
        this->z = arg3;
    }
};

//edit I guess I wasn't clear that the question isn't really "Can I?" but rather "How can I?". To be even more specific: What can I put in place of /*something here*/ to make setB() actually work the same as:

void setB(int arg1, int arg2, int arg3) {
    this->x = arg1;
    this->y = arg2;
    this->z = arg3; }
zamkot
  • 81
  • 7
  • 1
    have you tried it by yourself? i see no problem with that. also, consider what you want to achieve, this seems not to be a good idea in general. – JKreiser Jan 11 '17 at 22:53
  • You *can,* but be very careful here. If you're planning on referring to `B` objects through `A`, you might want to include a virtual destructor to get proper destruction behavior with polymorphic types in all contexts you might use them in, and have a look at [the slicing problem.](http://stackoverflow.com/questions/274626/what-is-object-slicing) – jaggedSpire Jan 11 '17 at 22:54
  • @jaggedSpire Can slicing cause issues in this case? I don't think it can, but maybe I'm wrong. – Brian Bi Jan 11 '17 at 23:01
  • @Brian I don't think in this *exact* case, but given OP is clearly keeping their assignment operators in their base class around, when they have some data that exists only in derived classes, it struck me as a good thing to warn OP about. – jaggedSpire Jan 11 '17 at 23:07

2 Answers2

2

Can I access the 'base part' of my object as if it were an object of its own?

Yes. It is a complete instance of the parent class, that lives inside the derived class instance.

A pointer or a reference to the derived class is convertible to a pointer/reference to the parent.

A non-pointer/reference i.e. a value of derived type is convertible to the parent as well, but that creates a copy of the parent subobject, just like converting any other value type to another always creates a copy.

Now I'd like to have a setter function for class B that acceses it's own members directly but assigns the derived members in batch using a temporary A object.

Simply cast this or the dereferenced reference to the parent class type:

 (A&)*this = A(arg1, arg2); // or
 *(A*)this = A(arg1, arg2);
eerorika
  • 232,697
  • 12
  • 197
  • 326
1

In /*something here*/ = A(arg1, arg2);, you can cast this to its base type and call it's implicit assignment operator

(*((A*)this))= A(arg1, arg2);
Jeandey Boris
  • 743
  • 4
  • 9