Computer Science Canada

Inheritance & Polymorphism Question.

Author:  copthesaint [ Thu Oct 10, 2013 10:23 pm ]
Post subject:  Inheritance & Polymorphism Question.

I have class a, class b and class c.

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?

Author:  Dreadnought [ Thu Oct 10, 2013 10:29 pm ]
Post subject:  Re: Inheritance & 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).
'

Author:  DemonWasp [ Thu Oct 10, 2013 11:34 pm ]
Post subject:  RE:Inheritance & 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).

Author:  copthesaint [ Fri Oct 11, 2013 3:36 am ]
Post subject:  RE:Inheritance & 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.

Author:  [Gandalf] [ Sat Oct 12, 2013 12:27 pm ]
Post subject:  RE:Inheritance & 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.


: