Search code examples
c++inheritancecastingparent

Cast object to parent


I have a problem with inheritance in C++. Here is what I would like to do:

class parent
{
   public:
   int a;
};

class son : public parent
{
   public:
   int b;
   operator parent()
   {
      parent p; p.a = a + b;
      return p;
   }
}


void funct(parent a)
{
    cout<<a.a;
}

son s; s.a = 3; s.b = 4;
funct(s);

And I would like it to print out 7. Instead, the casting is implicitly done without affecting anything, and 3 is printed out. Could anyone give me an advice on how to do this? Is this even possible?


Solution

  • According to the C++ Standard

    A conversion function is never used to convert a (possibly cv-qualified) object to the (possibly cv-qualified) same object type (or a reference to it), to a (possibly cv-qualified) base class of that type (or a reference to it), or to (possibly cv-qualified) void.

    You could use a virtual function that outputs data members or you could define operator << as pseudo-virtual (that is that calls a virtual function) for the classes.

    For example

    class parent
    {
       public:
       virtual std::ostream & out( std::ostream &os ) const { return os << a; }
       int a;
    };
    
    class son : public parent
    {
       public:
       int b;
       std::ostream & out( std::ostream &os ) const { return os << a + b; }
    };
    
    std::ostream & operator <<( std::ostream &os, const parent &obj )
    {
       return obj.out( os );
    }