Hello All,

I've been learning C++ recently and my question pertains to inheritance. What I have is code like this:

class shape {
public:
    virtual void print_type()=0;
    double delta() //acts the same on all shapes
};

class sphere : public shape {
public:
    void print_type() {
    cout << "this is a sphere" << endl;
    }

};

class cylinder : public shape {
public:
      void print_type() {
      cout << "this is a cylinder" << endl;
      }

};

I'd then like to take the shape as a datamember (or adding flowers to the shape as I use here :

class Shape_with_flowers {
protected:
  shape *the_shape;
public:
   // member functions

};

However, the shape with flowers will mean that the original member function delta() will act differently upon an instance of shape with flowers than on a pure shape on its own. I've thought that I can make Shape_with_flowers a derived class of shape and make delta virtual. However this seems inelegant to me, as the derived class uses the parent class as the data member, is there a better solution? A lot of the member functions in shape would apply fine to Shape_with_flowers, but some will be different.

Thank you.

Do you mean something like this:

struct shape
{
    virtual ~shape() {}
    virtual void print() const = 0 ;
    virtual double delta() const { return 1.0 ; }
    // ...
};

struct sphere : shape
{
    virtual void print() const { std::cout << "sphere\n" ; }
    // ...
};

struct cylinder : shape
{
    virtual void print() const { std::cout << "cylinder\n" ; }
    // ...
};

struct shape_with_flowers : shape
{
    shape_with_flowers( std::shared_ptr<shape> ss ) : s(ss) {}
    std::shared_ptr<shape> s ;
    virtual void print() const { std::cout << "with flower! " ; s->print() ; }
    virtual double delta() const { return s->delta() + 2.0 ; }
    // ...
};

This is fine; it is the decorator design pattern and may be the most elegant solution to the design problem.
http://www.vincehuston.org/dp/decorator.html

Yes, that's what I mean. I'm glad that it's used, thank you for your time.

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.