Reputation: 8940
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?
Upvotes: 0
Views: 637
Reputation: 4838
Object is automatically casting to parent class by method like this:
operator base_type&() {return (base_type&)*this;}
You can't change this method.
You can only change inheritance to protected or private. The compiler never do a implicit casting then, even if you define casting operator.
You can only write a ordinary method which can do that casting and call it, when you need.
Upvotes: 0
Reputation: 310980
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 );
}
Upvotes: 1
Reputation: 1334
This is how 7 will be printed:
funct(s.operator parent());
And one point to remember:
funct(s)
//would result in object slicing as the 'funct' takes base class object by value.
Upvotes: 0