should always return a pointer to class in interface design?

Viewed 8301

I wish I could return an object of virtual base class so that I won't need to deal with the memory management(the idea of function programming also stimulate this pursuit). That means I am looking for some things like below:

class Car
{
  public:
     virtual int price() = 0 ;
     virtual string brand() = 0 ;
}

class Interface
{
  public:
     virtual Car giveMeACar() = 0 ;
     virtual vector<Car> listMeAllTheCars() = 0 ;
}

However, this won't even compile due to that Car is an abstract interface, with an error message :

invalid abstract return type for member function 'virtual Car giveMeACar() = 0 ; because the following virtual functions are pure within 'Car' : int price()
string brand() ;

So, does that means I have to revise the interface to something like below and manager the memory myself (delete the instance after using it) - ruling out the option of using smart pointer.

class Interface
{
  public:
     virtual Car* giveMeACar() = 0 ;
     virtual vector<Car*> listMeAllTheCars() = 0 ;
}

My question is : is this the only option I have when design an interface where every things(class) is abstract?

Returning an object of interface class is perfect valid in Java. C++ seems to be litter bit verbose and counter intuitive in this facet. More than often, I feel C++ is "pointer to object programming language" instead of a "object programming language" because without a pointer you can not get too much benefit of object programming.

7 Answers

Alex B statement is correct, but to give an old question a modern solution(C++11) you should return a std::unique_ptr. This passes ownership of the car to the caller and the car will be automatically deleted when the caller goes out of scope

#include <memory>

class Car
{
public:
    virtual int price() = 0 ;
    virtual string brand() = 0 ;
};

class Interface
{
public:
    virtual std::uniqe_ptr<Car> giveMeACar() = 0 ;
    virtual vector<std::uniqe_ptr<Car>> listMeAllTheCars() = 0;
}
Related