Abstract classes and Pointers

2019-08-10 20:44发布

问题:

I have a class

// i want an abstract class.

class Foo
{
    public:
    virtual void bar()=0;
};

// i want this abstract calss to be used all over the program :) to enjoy polymorphism.

class EatFoo
{
public:
    vector<Foo> fooV; // not working
    vector<Foo *> fooPV;
};

I get a compile time error that abstract class cannot be instantiated.

Yes its true but i really want or i want to learn :

how to make other programmers "have to - have to" implement some function and i donot want to use pointers in my programs. [i donot know why ? but i have that gut feeling..]

Is there some pattern or something that can help me. With java it is all references and yup it is doable.

Thanks.

回答1:

If you want polymorphic behaviour for container items, you have no choice but to use pointers. To make your life as easy as possible, you should use smart pointers, such as shared_ptr<Foo>.



回答2:

Your gut is right... partly...

You shouldn't use raw pointers:

class EatFoo
{
public:
    vector<shared_ptr<Foo> > fooV;
};

There's no way in C++ to have collections of abstract objects.