virtual methods ?

Discussion in 'C++' started by Geiregat Jonas, Jun 23, 2003.

  1. I've seen some c++ code where before a method there was vitual ex:
    class foo{
    public:
    virtual bool method();
    }

    what does virtual do ?
     
    Geiregat Jonas, Jun 23, 2003
    #1
    1. Advertising

  2. Geiregat Jonas wrote:
    > I've seen some c++ code where before a method there was vitual ex:
    > class foo{
    > public:
    > virtual bool method();
    > }
    >
    > what does virtual do ?
    >


    Read your C++ text book or reference manual. If it doesn't
    explain virtual functions, then get a better one.

    See the FAQ:
    http://www.parashift.com/c -faq-lite/virtual-functions.html

    Always research the reference manual first, the FAQ second
    then search the newsgroups.

    --
    Thomas Matthews

    C++ newsgroup welcome message:
    http://www.slack.net/~shiva/welcome.txt
    C++ Faq: http://www.parashift.com/c -faq-lite
    C Faq: http://www.eskimo.com/~scs/c-faq/top.html
    alt.comp.lang.learn.c-c++ faq:
    http://www.raos.demon.uk/acllc-c /faq.html
    Other sites:
    http://www.josuttis.com -- C++ STL Library book
     
    Thomas Matthews, Jun 23, 2003
    #2
    1. Advertising

  3. Geiregat Jonas wrote:

    > I've seen some C++ code where before a method there was vitual ex:
    >
    > class foo{
    > public:
    > virtual bool method(void);
    > }
    >
    > what does virtual do?


    It means that an invocation of bool method(void)
    may actually resolve to the function definition
    for a class derived from foo.
     
    E. Robert Tisdale, Jun 23, 2003
    #3
  4. Geiregat Jonas

    Adie Guest

    David Cattarin wrote:

    >Adie <> wrote in message news:<>...
    >> Geiregat Jonas wrote:
    >>
    >> >I've seen some c++ code where before a method there was vitual ex:
    >> >class foo{
    >> >public:
    >> > virtual bool method();
    >> >}
    >> >
    >> >what does virtual do ?

    >>
    >> Adds a little spice.

    >[snip]
    >> Base* someObject;
    >> someObject = new DerivedB; // it's a DerivedB obj
    >> someObject->aVirtual(x);// does something else
    >>
    >> The point is that by making method aVirtual "virtual" the compiler allows
    >> access to each derived classes functions at runtime, otherwise you will be
    >> stuck with Base's.

    >
    >That's not quite right. Without virtual, the compiler chooses the
    >method based on the pointer type.
    >
    >Base* bObj;
    >Derived* dObj = new Derived;
    >bObj = dObj
    >
    >bObj->fn( ); // Calls B's version of fn( )
    >dObj->fn( ); // Calls D's version of fn( )


    Sorry, thought that was what I was getting at.

    Might this be a better example?

    Base* base;
    base = new Base;
    base->f(); // calls base version of f()
    delete base;
    base = new DerivedA;
    base->f(); // calls DerivedA version of f()
    delete base;
    base = NULL;

    I havent tried this, I'm guessing that it should be ok.
     
    Adie, Jun 24, 2003
    #4
  5. Geiregat Jonas

    Gavin Deane Guest

    Adie <> wrote in message news:<>...
    > Geiregat Jonas wrote:
    >
    > >I've seen some c++ code where before a method there was vitual ex:
    > >class foo{
    > >public:
    > > virtual bool method();
    > >}
    > >
    > >what does virtual do ?

    >
    > Adds a little spice.
    >
    > Actually, being as Those Who Know have decided that all C++ questions
    > should be directed to a FAQ


    Not all C++ questions, just the frequently asked ones. Do you see now?
     
    Gavin Deane, Jun 24, 2003
    #5
  6. Adie <> wrote in message news:<>...
    > David Cattarin wrote:
    >
    > >Adie <> wrote in message news:<>...
    > >> Geiregat Jonas wrote:
    > >>
    > >> >I've seen some c++ code where before a method there was vitual ex:
    > >> >class foo{
    > >> >public:
    > >> > virtual bool method();
    > >> >}
    > >> >
    > >> >what does virtual do ?
    > >>
    > >> Adds a little spice.

    > [snip]
    > >> Base* someObject;
    > >> someObject = new DerivedB; // it's a DerivedB obj
    > >> someObject->aVirtual(x);// does something else
    > >>
    > >> The point is that by making method aVirtual "virtual" the compiler allows
    > >> access to each derived classes functions at runtime, otherwise you will be
    > >> stuck with Base's.

    > >
    > >That's not quite right. Without virtual, the compiler chooses the
    > >method based on the pointer type.
    > >
    > >Base* bObj;
    > >Derived* dObj = new Derived;
    > >bObj = dObj
    > >
    > >bObj->fn( ); // Calls B's version of fn( )
    > >dObj->fn( ); // Calls D's version of fn( )

    >
    > Sorry, thought that was what I was getting at.
    >
    > Might this be a better example?
    >
    > Base* base;
    > base = new Base;
    > base->f(); // calls base version of f()
    > delete base;
    > base = new DerivedA;
    > base->f(); // calls DerivedA version of f()
    > delete base;
    > base = NULL;
    >
    > I havent tried this, I'm guessing that it should be ok.



    Not quite. When virtual is not used, the selection of the method is
    determined at compile time based on how the method is accessed; in our
    case we are talking about pointers.

    So, there is one mistake in your example:
    base = new DerivedA;
    base->f( ); // calls *** Base *** version of f( )

    Dave
     
    David Cattarin, Jun 24, 2003
    #6
  7. Geiregat Jonas

    Adie Guest

    David Cattarin wrote:
    >Adie <> wrote in message news:<>...
    >> David Cattarin wrote:
    >>
    >> >Adie <> wrote in message news:<>...
    >> >> Geiregat Jonas wrote:
    >> >>
    >> >> >I've seen some c++ code where before a method there was vitual ex:
    >> >> >class foo{
    >> >> >public:
    >> >> > virtual bool method();
    >> >> >}
    >> >> >
    >> >> >what does virtual do ?
    >> >>
    >> >> Adds a little spice.

    >> [snip]
    >> >> Base* someObject;
    >> >> someObject = new DerivedB; // it's a DerivedB obj
    >> >> someObject->aVirtual(x);// does something else
    >> >>
    >> >> The point is that by making method aVirtual "virtual" the compiler allows
    >> >> access to each derived classes functions at runtime, otherwise you will be
    >> >> stuck with Base's.
    >> >
    >> >That's not quite right. Without virtual, the compiler chooses the
    >> >method based on the pointer type.
    >> >
    >> >Base* bObj;
    >> >Derived* dObj = new Derived;
    >> >bObj = dObj
    >> >
    >> >bObj->fn( ); // Calls B's version of fn( )
    >> >dObj->fn( ); // Calls D's version of fn( )

    >>
    >> Sorry, thought that was what I was getting at.
    >>
    >> Might this be a better example?
    >>
    >> Base* base;
    >> base = new Base;
    >> base->f(); // calls base version of f()
    >> delete base;
    >> base = new DerivedA;
    >> base->f(); // calls DerivedA version of f()
    >> delete base;
    >> base = NULL;
    >>
    >> I havent tried this, I'm guessing that it should be ok.

    >
    >
    >Not quite. When virtual is not used, the selection of the method is
    >determined at compile time based on how the method is accessed; in our
    >case we are talking about pointers.
    >
    >So, there is one mistake in your example:
    > base = new DerivedA;
    > base->f( ); // calls *** Base *** version of f( )


    No it's ok, I was assuming (assumed that you'd assume too) that Base had a
    virtual void f()

    One thing that I havent discovered yet, is how to determine which type of
    derived object the dynamically assigned Base pointer is pointing to. For
    instance

    class Base // includes virtual void f() { cout << "Hello from Base";}
    class DerivedA : public Base //void f() { cout << "Hello from DerivedA";}
    class DerivedB : public Base //void f() { cout << "Hello from DerivedB";}

    int main (void)
    {
    std::vector<Base*> vBase;
    Base *base, *derivedA, *derivedB;
    base = new Base;
    derivedA = new DerivedA;
    derivedB = new DerivedB;
    vBase.push_back(base);
    vBase.push_back(derivedA);
    vBase.push_back(derivedB);

    for (int i = 0; i < vBase.size(); i++)
    {

    This is where i'm confused. How do I get the type of object each pointer
    in vBase is pointing to? Will value_type do it or will that just return
    Base? Haven't tried to compile this obviously.
    }
    }
     
    Adie, Jun 24, 2003
    #7
  8. "Adie" wrote:

    > One thing that I havent discovered yet, is how to determine which type of
    > derived object the dynamically assigned Base pointer is pointing to. For
    > instance
    >
    > class Base // includes virtual void f() { cout << "Hello from Base";}
    > class DerivedA : public Base //void f() { cout << "Hello from DerivedA";}
    > class DerivedB : public Base //void f() { cout << "Hello from DerivedB";}
    >
    > int main (void)
    > {
    > std::vector<Base*> vBase;
    > Base *base, *derivedA, *derivedB;
    > base = new Base;
    > derivedA = new DerivedA;
    > derivedB = new DerivedB;
    > vBase.push_back(base);
    > vBase.push_back(derivedA);
    > vBase.push_back(derivedB);
    >
    > for (int i = 0; i < vBase.size(); i++)
    > {
    >
    > This is where i'm confused. How do I get the type of object each pointer
    > in vBase is pointing to?


    The smart-ass (but mostly correct answer) is "why do you care?". After all,
    if you designed your class
    hierarchy correctly, the polymorphic behavior will occur via virtual
    functions without your knowing the
    type of the object.In you example above, presumably you would just call f(),
    and the correct f() will just
    be called without your having to worry about which type of derived class it
    is.

    > Will value_type do it or will that just return
    > Base?


    value_type is Base*. value_type is not polymorphic, it's just a typedef for
    what is stored in the vector,
    which in this case you've defined to be Base*.

    The less smart-ass answer is that if you absolutely, positively, must know
    the exact type of the object, you
    use the dynamic_cast operator. If you need more type info than dynamic_cast
    provides, you can use the
    type_id operator. But nine times out of ten - and maybe more frequently -
    the fact that you need to know
    the exact type of a polymorphic object is evidence of a design flaw in your
    code - you should just be using
    virtual functions, not if statements or switch statements that depend upon
    the type of the object.

    Best regards,

    Tom
     
    Michael Isenman, Jun 25, 2003
    #8
  9. Geiregat Jonas

    Adie Guest

    Michael Isenman wrote:
    >"Adie" wrote:
    >
    >> One thing that I havent discovered yet, is how to determine which type of
    >> derived object the dynamically assigned Base pointer is pointing to. For
    >> instance
    >>
    >> class Base // includes virtual void f() { cout << "Hello from Base";}
    >> class DerivedA : public Base //void f() { cout << "Hello from DerivedA";}
    >> class DerivedB : public Base //void f() { cout << "Hello from DerivedB";}
    >>
    >> int main (void)
    >> {
    >> std::vector<Base*> vBase;
    >> Base *base, *derivedA, *derivedB;
    >> base = new Base;
    >> derivedA = new DerivedA;
    >> derivedB = new DerivedB;
    >> vBase.push_back(base);
    >> vBase.push_back(derivedA);
    >> vBase.push_back(derivedB);
    >>
    >> for (int i = 0; i < vBase.size(); i++)
    >> {
    >>
    >> This is where i'm confused. How do I get the type of object each pointer
    >> in vBase is pointing to?

    >
    >The smart-ass (but mostly correct answer) is "why do you care?". After all,
    >if you designed your class
    >hierarchy correctly, the polymorphic behavior will occur via virtual
    >functions without your knowing the
    >type of the object.In you example above, presumably you would just call f(),
    >and the correct f() will just
    >be called without your having to worry about which type of derived class it
    >is.


    So if the for loop looks like;

    for (int i = 0; i < vBase.size(); i++)
    {
    Base* newBase;
    newBase = vBase;
    newBase->f();
    }

    it'll wade through the vector assigning to the Base pointer but will still
    call the correct f() for derived object? Is that right? Sounds kinda
    groovy if it is.

    >> Will value_type do it or will that just return
    >> Base?

    >
    >value_type is Base*. value_type is not polymorphic, it's just a typedef for
    >what is stored in the vector,
    >which in this case you've defined to be Base*.
    >
    >The less smart-ass answer is that if you absolutely, positively, must know
    >the exact type of the object, you
    >use the dynamic_cast operator. If you need more type info than dynamic_cast
    >provides, you can use the
    >type_id operator. But nine times out of ten - and maybe more frequently -
    >the fact that you need to know
    >the exact type of a polymorphic object is evidence of a design flaw in your
    >code - you should just be using
    >virtual functions, not if statements or switch statements that depend upon
    >the type of the object.


    Yes, I can see that would make it all very labour intensive.
     
    Adie, Jun 25, 2003
    #9
  10. Geiregat Jonas

    Adie Guest

    Corey Murtagh wrote:
    >Adie wrote:
    >> Michael Isenman wrote:

    ><snip>
    >>>The smart-ass (but mostly correct answer) is "why do you care?". After all,
    >>>if you designed your class
    >>>hierarchy correctly, the polymorphic behavior will occur via virtual
    >>>functions without your knowing the
    >>>type of the object.In you example above, presumably you would just call f(),
    >>>and the correct f() will just
    >>>be called without your having to worry about which type of derived class it
    >>>is.

    >>
    >> So if the for loop looks like;
    >>
    >> for (int i = 0; i < vBase.size(); i++)
    >> {
    >> Base* newBase;
    >> newBase = vBase;
    >> newBase->f();
    >> }
    >>
    >> it'll wade through the vector assigning to the Base pointer but will still
    >> call the correct f() for derived object? Is that right? Sounds kinda
    >> groovy if it is.

    >
    >Yes, that's exactly what the 'virtual' keyword is intended for. To test:
    >
    >-----------
    >#include <iostream>
    >
    >class Base
    >{
    >public:
    > virtual int f() const { return 1; }
    >};
    >
    >class Derived : public Base
    >{
    >public:
    > virtual int f() const { return 2; }
    >};
    >
    >int main()
    >{
    >Base* b = new Derived;
    > std::cout << b->f() << std::endl;
    > return 0;
    >}
    >-----------
    >
    >The above prints '2'... or should. If it doesn't then something is
    >seriously wrong.


    You know, I asked my lecturer about this a while back and she said that
    you had to find the type when extracting the pointer from a container, I
    thought at the time that it was a bit clumsy. She's actually a Java
    programmer and suggested it was easier in Java, kinda fundamentally wrong
    wasn't she.
     
    Adie, Jun 25, 2003
    #10
  11. Adie wrote:
    > Corey Murtagh wrote:

    <snip>
    >>
    >>The above prints '2'... or should. If it doesn't then something is
    >>seriously wrong.

    >
    > You know, I asked my lecturer about this a while back and she said that
    > you had to find the type when extracting the pointer from a container, I
    > thought at the time that it was a bit clumsy. She's actually a Java
    > programmer and suggested it was easier in Java, kinda fundamentally wrong
    > wasn't she.


    Yeah, it sounds that way. At the very least her statement was
    misleading. She shouldn't be 'teaching' things like this to students
    when she either doesn't know what she's talking about, or can't
    communicate it correctly.

    The only time you need to determine the true class of a polymorphic
    object is if you need to access methods which are first defined for that
    class. There are cases where this is desirable, which is most of the
    reason for dynamic_cast<>(). In a lot of cases though you can avoid it
    by designing your base class to provide all the interfaces you need for
    your derived classes.

    --
    Corey Murtagh
    The Electric Monk
    "Quidquid latine dictum sit, altum viditur!"
     
    Corey Murtagh, Jun 25, 2003
    #11
  12. Geiregat Jonas

    Adie Guest

    Corey Murtagh wrote:
    >Adie wrote:
    >>
    >> You know, I asked my lecturer about this a while back and she said that
    >> you had to find the type when extracting the pointer from a container, I
    >> thought at the time that it was a bit clumsy. She's actually a Java
    >> programmer and suggested it was easier in Java, kinda fundamentally wrong
    >> wasn't she.

    >
    >Yeah, it sounds that way. At the very least her statement was
    >misleading. She shouldn't be 'teaching' things like this to students
    >when she either doesn't know what she's talking about, or can't
    >communicate it correctly.


    Sadly the coverage of standard C++ was poor, three modules (classes) in
    total - the first gave us; void main() for which I promptly wrapped on
    the knuckles for using on Usenet, the second offered an intro into GUI
    toolkits with X, Athena and Qt whilst the third concentrated on using
    Borland CPP Builder libraries/GUI with some UML/Patterns stuff thrown in
    for good measure. I suppose they're worried that most people would become
    bored with three straight C++ modules, disadvantage being that we didn't
    get a good coverage of what are considered the basics.

    Oh well, there's always books and Usenet, I'll get there in the end :)

    >The only time you need to determine the true class of a polymorphic
    >object is if you need to access methods which are first defined for that
    >class. There are cases where this is desirable, which is most of the
    >reason for dynamic_cast<>(). In a lot of cases though you can avoid it
    >by designing your base class to provide all the interfaces you need for
    >your derived classes.


    Doesn't that go against the grain of keeping Base classes as lightweight
    as possible?
     
    Adie, Jun 25, 2003
    #12
  13. Adie wrote:

    > Corey Murtagh wrote:
    >
    >>Adie wrote:
    >>
    >>>You know, I asked my lecturer about this a while back and she said that
    >>>you had to find the type when extracting the pointer from a container, I
    >>>thought at the time that it was a bit clumsy. She's actually a Java
    >>>programmer and suggested it was easier in Java, kinda fundamentally wrong
    >>>wasn't she.

    >>
    >>Yeah, it sounds that way. At the very least her statement was
    >>misleading. She shouldn't be 'teaching' things like this to students
    >>when she either doesn't know what she's talking about, or can't
    >>communicate it correctly.

    >
    >
    > Sadly the coverage of standard C++ was poor, three modules (classes) in
    > total - the first gave us; void main() for which I promptly wrapped on
    > the knuckles for using on Usenet, the second offered an intro into GUI
    > toolkits with X, Athena and Qt whilst the third concentrated on using
    > Borland CPP Builder libraries/GUI with some UML/Patterns stuff thrown in
    > for good measure. I suppose they're worried that most people would become
    > bored with three straight C++ modules, disadvantage being that we didn't
    > get a good coverage of what are considered the basics.


    Unfortunately this seems to be a common trend. The perception that C++
    is "too difficult" compared to languages like Java and Visual Basic has
    really damaged the educational possibilities.

    > Oh well, there's always books and Usenet, I'll get there in the end :)


    As a self-taught programmer I've picked up an aweful lot of useful stuff
    online :>

    The downside is that I don't have a piece of paper to tell prospective
    employers that I'm able to do what I've *been* doing for the past 7
    years. Makes it rather difficult to get work, even though they claim
    we've got a shortage of C++ programmers over here at the moment.

    >>The only time you need to determine the true class of a polymorphic
    >>object is if you need to access methods which are first defined for that
    >>class. There are cases where this is desirable, which is most of the
    >>reason for dynamic_cast<>(). In a lot of cases though you can avoid it
    >>by designing your base class to provide all the interfaces you need for
    >>your derived classes.

    >
    > Doesn't that go against the grain of keeping Base classes as lightweight
    > as possible?


    Code-wise, not really. Your base class doesn't actually have to
    implement *any* of those interfaces if you really want it to stay light.
    All of the functionality can be implemented down the inheritence tree.

    That said, this is a fairly common structure in some areas:

    class base_object
    {
    public:
    base_object();
    virtual ~base_object();

    // some interfaces common to all derived
    //...
    };

    class derived1a : public base_object
    {
    public:
    derived1();
    virtual ~derived1();

    // common interfaces implemented in this class
    //...

    // new interfaces implemented for this branch
    //...
    };

    class derived1b : public base_object
    {
    // like derived1a, but with different new interfaces
    };

    etc. This allows you to store all of your derived objects in a
    base_object pointer, or vector of pointers, or whatever. Each branch
    then has to be identified at its branch point using dynamic_cast<>().
    So if I have a vector full of base_object*s and I need an interface
    that's only provided by objects descended from derived1b, I can filter
    the vector with dynamic_cast<>().

    It has its uses. It can simplify certain aspects of your programs, but
    overuse can make your code that much more difficult to read. Usually
    it's preferable to have a more complete interface in the base and
    provide implementation details in the descendants.


    --
    Corey Murtagh
    The Electric Monk
    "Quidquid latine dictum sit, altum viditur!"
     
    Corey Murtagh, Jun 26, 2003
    #13
  14. On Wed, 25 Jun 2003 18:32:17 +0100, Adie <>
    wrote:

    >Corey Murtagh wrote:
    >>Adie wrote:
    >>> Michael Isenman wrote:

    >><snip>
    >>>>The smart-ass (but mostly correct answer) is "why do you care?". After all,
    >>>>if you designed your class
    >>>>hierarchy correctly, the polymorphic behavior will occur via virtual
    >>>>functions without your knowing the
    >>>>type of the object.In you example above, presumably you would just call f(),
    >>>>and the correct f() will just
    >>>>be called without your having to worry about which type of derived class it
    >>>>is.
    >>>
    >>> So if the for loop looks like;
    >>>
    >>> for (int i = 0; i < vBase.size(); i++)
    >>> {
    >>> Base* newBase;
    >>> newBase = vBase;
    >>> newBase->f();
    >>> }
    >>>
    >>> it'll wade through the vector assigning to the Base pointer but will still
    >>> call the correct f() for derived object? Is that right? Sounds kinda
    >>> groovy if it is.

    >>
    >>Yes, that's exactly what the 'virtual' keyword is intended for. To test:
    >>
    >>-----------
    >>#include <iostream>
    >>
    >>class Base
    >>{
    >>public:
    >> virtual int f() const { return 1; }
    >>};
    >>
    >>class Derived : public Base
    >>{
    >>public:
    >> virtual int f() const { return 2; }
    >>};
    >>
    >>int main()
    >>{
    >>Base* b = new Derived;
    >> std::cout << b->f() << std::endl;
    >> return 0;
    >>}
    >>-----------
    >>
    >>The above prints '2'... or should. If it doesn't then something is
    >>seriously wrong.

    >
    >You know, I asked my lecturer about this a while back and she said that
    >you had to find the type when extracting the pointer from a container, I
    >thought at the time that it was a bit clumsy. She's actually a Java
    >programmer and suggested it was easier in Java, kinda fundamentally wrong
    >wasn't she.


    If she was a java programmer it is probably because in java there are
    no templates. All the standard containers store Objects, which is
    basically a Base type for every other java type. So when using a
    container you must cast all objects that you pull out of the container
    before you can use them. This is a huge flaw in java and, as I
    understand, version 1.5 will have some type of templates. So it was
    probably her way of doing things coming from java, but in C++ you
    don't need to do this, provided you use a template container with the
    interface you plan on using.
     
    Robert Groves, Jun 26, 2003
    #14
  15. "Adie" <> wrote in message
    news:...
    > >> This is where i'm confused. How do I get the type of object each

    pointer
    > >> in vBase is pointing to?

    > >
    > >The smart-ass (but mostly correct answer) is "why do you care?". After

    all,
    > >if you designed your class
    > >hierarchy correctly, the polymorphic behavior will occur via virtual
    > >functions without your knowing the
    > >type of the object.In you example above, presumably you would just call

    f(),
    > >and the correct f() will just
    > >be called without your having to worry about which type of derived class

    it
    > >is.

    >
    > So if the for loop looks like;
    >
    > for (int i = 0; i < vBase.size(); i++)
    > {
    > Base* newBase;
    > newBase = vBase;
    > newBase->f();


    I know I'm stating the obvious, but I'd substitute:
    vBase->f();
    for the above three lines. Less typing, plus it gets rid of the unneeded
    newBase variable.

    > }
    >
    > it'll wade through the vector assigning to the Base pointer but will still
    > call the correct f() for derived object? Is that right? Sounds kinda

    groovy
    > if it is.


    Welcome to C++, my friend.

    Best regards,

    Tom
     
    Thomas Tutone, Jun 26, 2003
    #15
  16. Geiregat Jonas

    Adie Guest

    Adie wrote:

    >Heh there's a UK university doing an MSc .NET, there's nothing like a well
    >rounded education, and that's nothing like a well a well rounded
    >education...


    For the record it's ".NET MSc in Distributed Systems Development"

    http://www2.dcs.hull.ac.uk/NETMSc/index.html
     
    Adie, Jun 26, 2003
    #16
  17. Adie wrote:
    >
    > >etc. This allows you to store all of your derived objects in a
    > >base_object pointer, or vector of pointers, or whatever. Each branch
    > >then has to be identified at its branch point using dynamic_cast<>().
    > >So if I have a vector full of base_object*s and I need an interface
    > >that's only provided by objects descended from derived1b, I can filter
    > >the vector with dynamic_cast<>().

    >
    > Sorry to be dense, but doesn't dynamic_cast<type id>(expression) just cast
    > expression to type id? Can you us it in an "if" statement?


    The trick with dynamic_cast ist the following:
    dynamic_cast also checks if the object you want to cast is really
    of the type you specify in the dynamic_cast. If you use it with
    pointers and the object is not of the required type you will
    get a 0 Pointer. And that is something you can detect.

    example:

    for (int i = 0; i < vBase.size(); i++)
    {
    Base* newBase;
    newBase = vBase;

    // now newBase could point to a Base object or to
    // DerivedA or DerivedB objects. Figure out which one

    // try to cast newBase to a DerivedA pointer.
    // But at runtime it should be checked, if the object newBase
    // points at is really a DerivedA

    DerivedA* pPtrA = dynamic_cast< DerivedA* >( newBase );
    if( pPtrA != 0 ) {
    // it was a DerivedA object
    }

    else {
    DerivedB* pPtr = dynamic_cast< DerivedB* >( newBase );
    if( pPtr != 0 ) {
    // it was a DerivedB object
    }
    else {
    // must have been a Base object
    }
    }
    }

    Now compare that with the simple use of a virtual function :)

    Additionally. Imagine you introduce a new class in about half a year:

    class DerivedC : public Base
    {
    ...
    };

    What do you have to do? Well, in the above you have to add some logic
    for the new class to detect it and add another if - else branch.

    And with the dispatch through virtual functions?
    Surprise: You have to do nothing! You just implement the function f()
    in the new class and the code you already had:

    for (int i = 0; i < vBase.size(); i++)
    {
    Base* newBase;
    newBase = vBase;
    newBase->f();
    }

    dispatches to DerivedC::f() whenver there is a pointer to DerivedC
    stored in the container. You don't even have to recompile the above
    loop!


    > >It has its uses. It can simplify certain aspects of your programs, but
    > >overuse can make your code that much more difficult to read. Usually
    > >it's preferable to have a more complete interface in the base and
    > >provide implementation details in the descendants.

    >
    > Might delegation also be used for this kind of problem, wrap the class
    > with the added functionality?


    Since the goal is to store pointers in a container and use
    polymorphism, this is not a good idea. If you want to make
    use of polymorphism to your advantage, then creating a complete
    interface in the base class is often far less work then any other
    option.

    --
    Karl Heinz Buchegger
     
    Karl Heinz Buchegger, Jun 26, 2003
    #17
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Derek Simmons
    Replies:
    0
    Views:
    819
    Derek Simmons
    Aug 1, 2004
  2. Jéjé
    Replies:
    2
    Views:
    409
    Jéjé
    Nov 30, 2005
  3. while_1
    Replies:
    2
    Views:
    645
    Roedy Green
    Jun 25, 2004
  4. Jim Fischer
    Replies:
    3
    Views:
    454
    Jim Fischer
    Jul 31, 2003
  5. Kenneth McDonald
    Replies:
    5
    Views:
    355
    Kenneth McDonald
    Sep 26, 2008
Loading...

Share This Page