Best return type of an accessor to void*

Discussion in 'C++' started by Brian Withun, Aug 20, 2007.

  1. Brian Withun

    Brian Withun Guest

    I have a base class (B) and several derived classes (D1, D2, ...)

    I have a container class (C) with an attribute (void *d) which is
    intended to point to any of D1, D2,...

    My question is, on my C::GetObject() accessor, what is the most
    appropriate return type?

    void* C::GetObject( void ) { return d; }

    or

    B* C::GetD( void ) { return (B*) d; }


    Is there any galvanizing rationale as to why I'd choose one return
    type over the other, or is there yet another possibility I have not
    considered?

    TIA

    Brian Herbert Withun
     
    Brian Withun, Aug 20, 2007
    #1
    1. Advertisements


  2. [[disregard the C::GetD() above, my intended illustration is below]]


    void* C::GetObject( void ) { return d; }

    or

    B* C::GetObject( void ) { return (B*) d; }
     
    Brian Herbert Withun, Aug 20, 2007
    #2
    1. Advertisements

  3. Brian Withun

    Jim Langston Guest

    Your container class shoudl have an attribute of Base *d instead of a void*.

    And, yes, return a B*
     
    Jim Langston, Aug 20, 2007
    #3
  4. Why isn't it a B*? If D1, D2, etc derive from B, make it a B*.
    If you want ot be able to store things that are not always derived
    from B, then another possibility is to make C a template class.

    template<typename T>
    class C
    {
    private:
    //Some type of data structures to store multiple instances of T.
    std::list<T*> internal_list; //example
    std::vector<T*> internal_vec; //example

    public:
    T* GetObject();
    };



    Then you would create instances of C as follows:

    C<D1> first;
    D1* d1 = first.GetObject();

    C<D2> second;
    D2* d2 = second.GetObject();

    C<NotDerivedFromB> third;
    NotDerivedFromB* ndfb = third.GetObject();
     
    Zachary Turner, Aug 20, 2007
    #4
  5. Oh, an there also a style mistake here. Please, drop the 'void'
    between parentheses, it's so C.
    It would probably be worth mentioning that in the derived classes of
    'C' (if any), you could even return a D1* or a D2* or..., since it
    would be a *covariant* type.

    V
     
    Victor Bazarov, Aug 20, 2007
    #5
  6. Thanks for the suggestion. I'm going to go this way because it has
    that intangible measure of elegance, and it makes the purpose of the
    code more evident when reading it for the first time. Upon reading
    your response I had the experience of, "now why didn't *I* think of
    that?"


    Brian Herbert Withun
     
    Brian Herbert Withun, Aug 20, 2007
    #6
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.