Boost logo

Boost Users :

From: Ruediger Berlich (ruediger.berlich_at_[hidden])
Date: 2008-08-21 08:47:07


Hi there,

after making what I then thought was a bad mistake, I discovered that the
code below actually works (gcc 4.3.1, OpenSUSE 11 64bit, Boost 1.36). I.e.,
there is an implicit cast from shared_ptr<derived> to shared_ptr<base> to
make it fit the function argument, although both represent different types.

Is this intended behaviour (i.e. portable) ? I did not find a corresponding
description in the docu.

Thanks and Best Regards,

Ruediger

/**************************************************************************/

#include <iostream>
#include <boost/shared_ptr.hpp>

class base{
public:
  virtual ~base(){}
  virtual void print() const {
    std::cout << "Hello world from base" << std::endl;
  }
};

class derived
  :public base
{
public:
  void print() const {
    std::cout << "Hello world from derived" << std::endl;
  }
};

void executeBasePrint(const boost::shared_ptr<base>& base_ptr){
  base_ptr->print();
}

main(){
  boost::shared_ptr<derived> derived_ptr(new derived());
  // Results in "Hello world from derived"
  executeBasePrint(derived_ptr);
}


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net