CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 13 of 13
  1. #1
    Join Date
    Oct 2002
    Posts
    359

    Weird Problem: delegation or inheritance

    As we know, delegation and inheritance can realize the same functionality.

    For example,
    class A : public B
    {
    virtual double fun();
    }

    and


    calss A
    {
    double fun()
    {
    b_.fun();
    }
    private:
    B b_;
    }

    In general, I can choose either one. However, in my program I can only use the delegation method. If the inheritance is used, it will cause weird behavior of other part of the code.

    Any one has any clue what is going?

    Thanks in advance.

  2. #2
    Join Date
    Apr 2004
    Location
    In the back seat of New Horizons.
    Posts
    1,238

    Re: Weird Problem: delegation or inheritance

    What weird behavior? Also, what is the specific example? Just curious...

  3. #3
    Join Date
    Jun 2002
    Posts
    1,417

    Re: Weird Problem: delegation or inheritance

    The two are different. With inheritence, method fun() was overridden in class A, hiding the function in the base class B. Even if fun() is called from B it will actually use the method defined in A because fun() is virtual. In order to call B::func() you have to explicitely tell the compiler you want the method in B
    Code:
    class B
    {
    public:
       virtual double fun() 
       {
            cout << "class B" << endl;
            return 0;
       }
       int foo()
       {
             fun(); // this calls A::fun();
            B::fun(); // this calls B::fun();
    		return 0;
       }
    
    };
    
    class A : public B
    {
    public:
       virtual double fun() 
       {
            cout << "class A" << endl;
            return 0;
       }
       int somefn()
       {
            fun(); // this calls A::fun();
            B::fun(); // this calls B::fun();
    		return 0;
       }
    };
    int main(int argc, char* argv[])
    {
    	A a;
    	a.somefn();
    	a.foo();
    	return 0;
    }
    Last edited by stober; December 22nd, 2005 at 11:15 PM.

  4. #4
    Join Date
    Sep 2004
    Location
    A Planet Called Earth... :-)
    Posts
    835

    Re: Weird Problem: delegation or inheritance

    Code:
    class A : public B
    {
    virtual double fun();  
    }
    
    and
    
    
    calss A
    {
    double fun() // Not virtual in base
    {
    b_.fun();
    }
    private:
    B b_;
    }
    C++ program ran... C++ program crashed... C++ programmer quit !!

    Regards

    Shaq

  5. #5
    Join Date
    Nov 2003
    Location
    Belgium
    Posts
    8,150

    Re: Weird Problem: delegation or inheritance

    Quote Originally Posted by caperover2002
    Any one has any clue what is going?
    No.
    You need to give much more information.
    What exactly do you mean with "weird behavior"?
    You probably need to post some code you are using.
    Marc Gregoire - NuonSoft (http://www.nuonsoft.com)
    My Blog
    Wallpaper Cycler 3.5.0.97

    Author of Professional C++, 4th Edition by Wiley/Wrox (includes C++17 features)
    ISBN: 978-1-119-42130-6
    [ http://www.facebook.com/professionalcpp ]

  6. #6
    Join Date
    Nov 2003
    Location
    Belgium
    Posts
    8,150

    Re: Weird Problem: delegation or inheritance

    [ merged threads ]

    Please do not post the same question in multiple threads.
    Marc Gregoire - NuonSoft (http://www.nuonsoft.com)
    My Blog
    Wallpaper Cycler 3.5.0.97

    Author of Professional C++, 4th Edition by Wiley/Wrox (includes C++17 features)
    ISBN: 978-1-119-42130-6
    [ http://www.facebook.com/professionalcpp ]

  7. #7
    Join Date
    Feb 2005
    Location
    "The Capital"
    Posts
    5,306

    Re: Weird Problem: delegation or inheritance

    You code in current state is totally flawed. Why not post some valid compilable code that you have made to show your confusion or whatever and then let us know the expected results and the results that you are actually getting. People will be in a better position to comment then. Delegates/Delegation is nothing but function pointers / member function pointers in C++ and hence the approach could be a lot different from what inheritance achieves. I am not able to understand what you are actually trying to derive from all this. Regards.

  8. #8
    Join Date
    Oct 2002
    Posts
    359

    Re: Weird Problem: delegation or inheritance

    Thanks for all replies.

    In another part of my program, I have a function fun1() calling function fun2() like:

    void fun2()
    {

    bool bGood=fun1();
    }

    bool fun1()
    {
    return false;
    }

    As we see, fun1() always returns false. However, when I debug it, I notice that in fact bGood is true!

    I guess if I use the inheritance, some memory or stack is damaged and as a result the returned value is not correct.

    Anyone has any idea why?

    Thanks.
    Last edited by caperover2002; December 23rd, 2005 at 12:29 PM.

  9. #9
    Join Date
    Oct 2002
    Posts
    359

    Re: Weird Problem: delegation or inheritance

    Quote Originally Posted by exterminator
    You code in current state is totally flawed. Why not post some valid compilable code that you have made to show your confusion or whatever and then let us know the expected results and the results that you are actually getting. People will be in a better position to comment then. Delegates/Delegation is nothing but function pointers / member function pointers in C++ and hence the approach could be a lot different from what inheritance achieves. I am not able to understand what you are actually trying to derive from all this. Regards.

    well, I understand what you are talking about. It is just a small part of a big project. Honestly, I could not duplicate this problem in another simplified context. I guess it can only be figured out on my own, but I need helps from you guys.

    Here is the class that causes the problem:

    class ContingentCompoundOption : public CreditLib::CompoundOption2
    {
    public:
    ContingentCompoundOption(const boost::shared_ptr<QuantLib::StochasticProcess>& process,
    const boost::shared_ptr<QuantLib::StrikedTypePayoff>& payoff1,
    const boost::shared_ptr<QuantLib::Exercise>& exercise1,
    const boost::shared_ptr<QuantLib::StrikedTypePayoff>& payoff2,
    const boost::shared_ptr<QuantLib::Exercise>& exercise2,
    const QuantLib::Handle<CreditLib::CreditTermStructure>& creditCurve,
    const boost::shared_ptr<QuantLib::PricingEngine>& engine =boost::shared_ptr<QuantLib::PricingEngine>())
    : CompoundOption2(process,payoff1,exercise1,payoff2,exercise2,engine)
    {
    }

    virtual ~ContingentCompoundOption(void)
    {
    }

    double price() { return 0.0; }

    private:

    };

    If this class is not instantiated anywhere, that is also fine. Whenever I use it, the problem appears. If I change the inheritance to delegation, it works fine.

    I want to understand why.

    Any clues, hints, thoughts will be really appreciated. Thanks.
    Last edited by caperover2002; December 23rd, 2005 at 10:05 PM.

  10. #10
    Join Date
    Oct 2000
    Location
    London, England
    Posts
    4,773

    Re: Weird Problem: delegation or inheritance

    This is the difference between using an abstract base class an delegation:
    Code:
    // delegation:
    class AImpl;
    
    class A
    {
    public:
       void func();
    private:
        AImpl * pImpl; // used to implement func()
    };
    
    // in compilation unit:
    void A::func()
    {
      pImpl->func();
    }
    your compilation unit will also be responsible for creating and destroying the pImpl. And because it's a pointer you must take care of copy-construction and assignment, or disable them.
    Code:
    // Now inheritance:
    
    class B
    {
    public:
       virtual ~B() {}
       virtual void func() = 0;
    };
    
    // to get an instance of a B
    B* createB();
    // or
    class BFactory
    {
    public:
       virtual B* createB()  = 0;
       virtual ~BFactory() {}
    };
    // and create a class or classes that implement B
    class BImpl : public B
    {
    public:
       virtual void func(); // virtual keyword optional here
    };
    // and somewhere
    void BImpl::func()
    {
     // implement it here
    }
    Which one to use depends on you. There can be some performance advantages of using a pImpl (delegation) because the compiler may be able to inline the function call to the pImpl and if it can then inline the implementation too you will see advantages. If it's a heavily used function that shows up in profiling to be a bottleneck then see if you can optimise by using a pImpl rather than inheritance.

    The other advantage of using a pImpl is that you can create an instance of the class (rather than use a factory or method to get you a pointer to one) which means you can create it yourself on the stack, and let the class itself sort out the RAII issues of its implementation pointer. With inheritance, there is no choice but to create a pointer, which you then have to delete. Of course you can use smart-pointers, and even std::auto_ptr might suffice.

    Inheritance should always be used of course if there are multiple methods of implementing the class. There are a couple of other reasons where this method is a good idea, particularly with regards to exporting across libraries.

  11. #11
    Join Date
    Oct 2002
    Posts
    359

    Re: Weird Problem: delegation or inheritance

    Quote Originally Posted by NMTop40
    This is the difference between using an abstract base class an delegation:
    Code:
    // delegation:
    class AImpl;
    
    class A
    {
    public:
       void func();
    private:
        AImpl * pImpl; // used to implement func()
    };
    
    // in compilation unit:
    void A::func()
    {
      pImpl->func();
    }
    your compilation unit will also be responsible for creating and destroying the pImpl. And because it's a pointer you must take care of copy-construction and assignment, or disable them.
    Code:
    // Now inheritance:
    
    class B
    {
    public:
       virtual ~B() {}
       virtual void func() = 0;
    };
    
    // to get an instance of a B
    B* createB();
    // or
    class BFactory
    {
    public:
       virtual B* createB()  = 0;
       virtual ~BFactory() {}
    };
    // and create a class or classes that implement B
    class BImpl : public B
    {
    public:
       virtual void func(); // virtual keyword optional here
    };
    // and somewhere
    void BImpl::func()
    {
     // implement it here
    }
    Which one to use depends on you. There can be some performance advantages of using a pImpl (delegation) because the compiler may be able to inline the function call to the pImpl and if it can then inline the implementation too you will see advantages. If it's a heavily used function that shows up in profiling to be a bottleneck then see if you can optimise by using a pImpl rather than inheritance.

    The other advantage of using a pImpl is that you can create an instance of the class (rather than use a factory or method to get you a pointer to one) which means you can create it yourself on the stack, and let the class itself sort out the RAII issues of its implementation pointer. With inheritance, there is no choice but to create a pointer, which you then have to delete. Of course you can use smart-pointers, and even std::auto_ptr might suffice.

    Inheritance should always be used of course if there are multiple methods of implementing the class. There are a couple of other reasons where this method is a good idea, particularly with regards to exporting across libraries.

    Thanks, but still don't see why it makes difference in my case.

  12. #12
    Join Date
    Oct 2002
    Posts
    359

    Re: Weird Problem: delegation or inheritance

    who can take a guess?

  13. #13
    Join Date
    Oct 2002
    Posts
    359

    Re: Weird Problem: delegation or inheritance---MORE INFORMATION AVAILABLE

    Here is the context of the problem:


    I have a base class

    class B
    {
    public:
    virtual bool fun() =0;
    }

    and two derived classes

    class A : public B
    {
    public:
    virtual bool fun()
    {
    return false;
    }

    }

    and

    class C : public B
    {
    public:
    virtual bool fun()
    {
    return false;
    }

    }

    One thing that is very interesting is that if the following line appears anywhere in my managed code, whether it is executed or not,

    A a;

    the function C:fun's return value will become true.


    What I am trying to understand is the difference it makes with or without "A a". Any hint or suggestion will be really appreciated!
    Last edited by caperover2002; January 5th, 2006 at 09:30 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured