
-----------------------------------
copthesaint
Thu Oct 10, 2013 10:23 pm

Inheritance &amp; Polymorphism Question.
-----------------------------------
I have class a, class b and class c.

Class A;

Class B : public A;

Class C:
protected:
A a;
B b;
};

My question is if I can use Polymorphism  to possibly cast C to type "A" or to type "B" without inheriting them both. If I included both A & B I could cast to either, but wouldn't this cause an issue for the multiple inheritance of methods and data types?

-----------------------------------
Dreadnought
Thu Oct 10, 2013 10:29 pm

Re: Inheritance &amp; Polymorphism Question.
-----------------------------------
Why not just have C inherit from B? Then C "is a" B and B "is a" A, hence C "is a" A (transitivity).

Maybe I don't understand the situation. You could also overload the cast operator to return a pointer to the objects of class A and B inside the object of class C (I'd recommend using inheritance if possible though).
'

-----------------------------------
DemonWasp
Thu Oct 10, 2013 11:34 pm

RE:Inheritance &amp; Polymorphism Question.
-----------------------------------
Technically, C++ does actually support multiple inheritance. Unless you know exactly what you're doing it's a disaster.

Dreadnought is right, though: if you want "C is an A" and "C is a B" and you already have "B is an A" then have C extend B. This doesn't require multiple inheritance (or overloading cast operators or anything else so complicated).

-----------------------------------
copthesaint
Fri Oct 11, 2013 3:36 am

RE:Inheritance &amp; Polymorphism Question.
-----------------------------------
As the example shows, I want a separate instance of both type A and B.

I tested my own question for a while and yea its exactly as you say; Unless you know exactly what you're doing it's a disaster. It took a little while but I came up with a solution with multiple inheritance. I'll test it for a while to see if there are any issues.

-----------------------------------
[Gandalf]
Sat Oct 12, 2013 12:27 pm

RE:Inheritance &amp; Polymorphism Question.
-----------------------------------
I've found that even if you know what you're doing with MI, and you get things working smoothly, you eventually realize there is a better way of doing it using SI.  You never need multiple inheritance.
