vlad_tepesch
vlad_tepesch

Reputation: 6891

assign to base component of a derived class

How can i assign a base class instance to the base class "member" of a derived class from the derived class?

class A{
public:
   A();
   A(const A& i);
   A &operator =(const A& i);
   ~A();
};

class B: public A{
public:
  void f(){
    A a;
    // calc(a);
    *this = a; // <- how?
  }
  void x(){};
private:
  int i;
};

Upvotes: 1

Views: 53

Answers (2)

vlad_tepesch
vlad_tepesch

Reputation: 6891

another obvious way (how could i miss this at the first place??) is to directly call the assignment operator of the base class:

A::operator=(a);

Upvotes: 1

Kijewski
Kijewski

Reputation: 26022

The most simple solution is to use dynamic_cast:

dynamic_cast<A &>(*this) = a;

Upvotes: 1

Related Questions