Copy Constructors and C ++ Base Classes

I would like to be able to initialize a derived class from a base class, for example:

class X {
   public:
   X() : m(3) {}
   int m;
};

class Y : public X {
   public: 
   Y() {}
   Y(const & X a)  : X(a) {}
};

Is there anything dangerous or unusual doing this? I want this because I deserialize a bunch of objects that are of the type I don’t know right away, so I basically want to use X as a temporary storage while I read the entire serialized file and then create my objects Y (and W, X, Y objs, depending on the data) using this data afterwards. Maybe there is an easier way that I am missing.

Thanks!

+3
source share
2 answers

, X ctor ( ), Y ( ) .

, Y Y ?

, Y X , :

Y( X const & a)   // the X was in an invalid place before
+5

- , ?

Y - ( ), .

class Y : public X {
   public: 
   Y() {}
   Y(const X& a) : X(a)
   {
     //'n' hasn't been initialized!
   }
   int n;
};

Y - , ? , X?

, X , , .

, , (Y "" X Y "- " X "):

class IAnInterface
{
public:
  virtual ~IAnInterface();
  virtual void SomeMethod() = 0;
  virtual void AnotherMethod() = 0;
}

class Y : public IAnInterface {
  public: 
  Y(const X& x) : m_x(x)
  {
  }
  X m_x;
  virtual void SomeMethod() { ... an implementation ... }
  virtual void AnotherMethod() { ... another implementation ... }
};
+3

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


All Articles