Hello,

This is probably a simple question.
I have a class A, and a class B, class C class... which inherits from class A.

Now I want to store it in a container e.g. vector

vector<*A> container;

I have also created some objects of B and C, and stored it in the container

B b;
C c;
container.push_back(&b);
container.push_back(&c);

Now for my question, I have overloaded << which take b, or c and print whatever it contains. Is it possible to fetch b, and c from the container so I can use <<?
As of now I have to written a print() function, which I call by
(*it)->print();

to print the information in the object. But is it possible to fetch from the container so I can use the overloaded << instead?

Recommended Answers

All 3 Replies

1. Probably you want vector<A*> , not a senseless vector<*A> ;)
2. >I have also created some objects of B and C, and stored it in the container...
It's not a container of class A or B or what else objects. It's a container of pointers to class A objects, feel the difference. You must provide an existence of pointed objects outside of the container otherwise contained pointers will point to nowhere. So you don't store b and c in the conatiner. You store pointers to these objects.
3. You have a homogeneous container of A* so you can't use polymorphic behaviour of A-B-C objects in ordinar functions operator<<(ostream&,const Class&) directly. Try this method:

class A {
public:
    virtual ~A() {}
    virtual ostream& print(ostream& os) const {
        return os << "A";
    }
};
class B: public A {
public:
    ostream& print(ostream& os) const {
        return os << "B"; // or what else...
    }
};
class C: public B {
public:
    ostream& print(ostream& os) const {
        return os << "C";
    }
};
ostream& operator<<(ostream& os,const A& p)
{
    return p.print(os); // polymorphism works!
}
int main()
{
    vector<A*> v;
    v.push_back(new A);
    v.push_back(new B);
    v.push_back(new C);
    for (size_t i = 0; i < v.size(); i++)
        cout << *v[i] << '\n';
    for (size_t i = 0; i < v.size(); i++)
        delete v[i]; // don't forget to free!
    return 0;
}

*v
that part what I was looking for, thanks.

Yes I've already written a virtual function.

Anyway thanks, and thanks for correcting me as well ^^;

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.