Saturday, December 17, 2011

C++ inheritance, polymorphism with the overloaded<< operator?

I have base class A and subclasses B, C, and D. A has a variable in that class that B, C, and D all use. A also has another variable called type (a string) that are for B and C. D also has a variable called type (an int) that I'm trying to override polymorphically over the type variable in the base class. I have a binary search tree class that each node points to an A object For testing, I currently have one A object that was instantiated from a D object and hangs on the binary search tree as an A object with variables from D as well. I can't figure out to print the variables from D and A that it has. I can print operator%26lt;%26lt; from the subclass or superclass, but it only will print the variables from the parent class. how can I print all of my variables? Open to moving variables...|||First, member variables aren't polymorphic, functions are. D has int type;, B and C have string type;, whether A has a type or not is irrelevant. What matters is that there has to be a virtual function in A which does something different depending on run-time type of A (whether it's really B or if it's really D)



For example, that function could return printable string representation of the type:



#include %26lt;iostream%26gt;

#include %26lt;string%26gt;

#include %26lt;sstream%26gt;

class A

{

聽聽聽聽 virtual std::string gettype_as_string() const = 0;

public: virtual ~A() {}

聽聽聽聽 friend std::ostream%26amp; operator%26lt;%26lt;(std::ostream%26amp; s, const A%26amp; a)

聽聽聽聽 {

聽聽聽聽聽聽聽聽 return s %26lt;%26lt; a.gettype_as_string();

聽聽聽聽 }

};

class B : public A

{

聽聽聽聽 std::string type;

聽聽聽聽 std::string gettype_as_string() const { return type; }

public: B(const std::string%26amp; t) : type(t) {}

};

class D : public A

{

聽聽聽聽 int type;

聽聽聽聽 std::string gettype_as_string() const { std::ostringstream os; os %26lt;%26lt; type; return os.str(); }

public: D(int i) : type(i) {}

};

int main()

{

聽聽聽聽 A* d = new D(1);

聽聽聽聽 std::cout %26lt;%26lt; "A created from D(1) prints " %26lt;%26lt; *d %26lt;%26lt; '\n';

聽聽聽聽 delete d;

聽聽聽聽 A* b = new B("hi");

聽聽聽聽 std::cout %26lt;%26lt; "A created from B(\"hi\") prints " %26lt;%26lt; *b %26lt;%26lt; '\n';

聽聽聽聽 delete b;

}

No comments:

Post a Comment