C++ design question

From: Simon Elliott (Simon)
Date: 09/28/04

  • Next message: Alan J. White: "BCS SPA-NE (formerly NOOPS) - Autumn 2004 Programme"
    Date: 28 Sep 2004 10:42:56 GMT
    
    

    I've been advised by the guys over on comp.lang.c++ to post this here
    to see if anyone can recommend a design improvement. In the following
    code example, the base class depends on an object in a derived class:
    fooBase has a reference to an object in fooDerived. It's been pointed
    out that this is potentially unsafe if bar_base_ref_ is accessed in the
    fooBase constructor.

    Can anyone improve on this aspect of the design? Here's the code:

    class barBase
    {
    protected:
      int i1_;
    public:
      barBase(int i1):i1_(i1){}
      virtual ~barBase(void){};
      void SetI1(int i1){i1_ = i1;}
    };

    class barDerived:public barBase
    {
    protected:
      int i1_;
      int i2_;
    public:
      barDerived(int i1, int i2):i2_(i2),barBase(i1){}
      virtual ~barDerived(void){};
    };

    class fooBase
    {
    private:
      barBase &bar_base_ref_;
    private:
      fooBase(const fooBase &C);
      fooBase& operator=(const fooBase &C);
    public:
      fooBase(barBase &bar_base_ref):bar_base_ref_(bar_base_ref){}
      virtual ~fooBase(void){};
      void DoStuffWithBarBase(void)
      {
        bar_base_ref_.SetI1(13);
      }
    };

    class fooDerived:public fooBase
    {
    private:
      barDerived my_bar_derived_;
    public:
      fooDerived(int i1, int i2):fooBase(my_bar_derived_),
           my_bar_derived_(42,43){}
      virtual ~fooDerived(void){};
    };

    int main(int argc, char **argv)
    {
      fooDerived my_foo_derived(42,1);
      my_foo_derived.DoStuffWithBarBase();
      return 0;
    }
     

    -- 
    Simon Elliott    http://www.ctsn.co.uk
    

  • Next message: Alan J. White: "BCS SPA-NE (formerly NOOPS) - Autumn 2004 Programme"

    Relevant Pages

    • Re: C++ design question
      ... "Simon Elliott" wrote: ... > to see if anyone can recommend a design improvement. ... > fooBase has a reference to an object in fooDerived. ...
      (comp.object)
    • Issue with moving a common method to base class
      ... class DistributionFoo: FooBase ... private void DoSomething() ...
      (microsoft.public.dotnet.general)
    • Re: C++ design question
      ... > to see if anyone can recommend a design improvement. ... the base class depends on an object in a derived class: ... > fooBase has a reference to an object in fooDerived. ... Then don't use it in the fooBase constructor:) ...
      (comp.object)
    • error LNK2019: unresolved external symbol
      ... class FooBase ... class Foo: virtual public FooBase ... int GetNumber; ...
      (microsoft.public.vc.language)
    • Re: C++ design question
      ... the base class depends on an object in a derived class: ... > fooBase has a reference to an object in fooDerived. ...
      (comp.object)