C++Talk.NET Forum Index C++Talk.NET
C++ language newsgroups
 
Archives   FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

virtual methods ?
Goto page 1, 2  Next
 
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ language (comp.lang.c++)
View previous topic :: View next topic  
Author Message
Geiregat Jonas
Guest





PostPosted: Mon Jun 23, 2003 9:17 pm    Post subject: virtual methods ? Reply with quote



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

what does virtual do ?

Back to top
Thomas Matthews
Guest





PostPosted: Mon Jun 23, 2003 9:24 pm    Post subject: Re: virtual methods ? Reply with quote



Geiregat Jonas wrote:
Quote:
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


Back to top
E. Robert Tisdale
Guest





PostPosted: Mon Jun 23, 2003 9:44 pm    Post subject: Re: virtual methods ? Reply with quote



Geiregat Jonas wrote:

Quote:
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.


Back to top
Adie
Guest





PostPosted: Tue Jun 24, 2003 1:49 pm    Post subject: Re: virtual methods ? Reply with quote

David Cattarin wrote:

Quote:
Adie <a_usenetizen (AT) hotmail (DOT) com> wrote

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.

Back to top
Gavin Deane
Guest





PostPosted: Tue Jun 24, 2003 2:52 pm    Post subject: Re: virtual methods ? Reply with quote

Adie <a_usenetizen (AT) hotmail (DOT) com> wrote

Quote:
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?

Back to top
David Cattarin
Guest





PostPosted: Tue Jun 24, 2003 5:45 pm    Post subject: Re: virtual methods ? Reply with quote

Adie <a_usenetizen (AT) hotmail (DOT) com> wrote

Quote:
David Cattarin wrote:

Adie <a_usenetizen (AT) hotmail (DOT) com> wrote

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

Back to top
Adie
Guest





PostPosted: Tue Jun 24, 2003 7:14 pm    Post subject: Re: virtual methods ? Reply with quote

David Cattarin wrote:
Quote:
Adie <a_usenetizen (AT) hotmail (DOT) com> wrote

David Cattarin wrote:

Adie <a_usenetizen (AT) hotmail (DOT) com> wrote

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 *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.
}
}



Back to top
Michael Isenman
Guest





PostPosted: Wed Jun 25, 2003 2:02 am    Post subject: Re: virtual methods ? Reply with quote

"Adie" wrote:

Quote:
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 *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.

Quote:
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




Back to top
Adie
Guest





PostPosted: Wed Jun 25, 2003 3:54 pm    Post subject: Re: virtual methods ? Reply with quote

Michael Isenman wrote:
Quote:
"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 *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[i];
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.

Quote:
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.

Back to top
Adie
Guest





PostPosted: Wed Jun 25, 2003 5:32 pm    Post subject: Re: virtual methods ? Reply with quote

Corey Murtagh wrote:
Quote:
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[i];
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.

Back to top
Corey Murtagh
Guest





PostPosted: Wed Jun 25, 2003 7:08 pm    Post subject: Re: virtual methods ? Reply with quote

Adie wrote:
Quote:
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!"


Back to top
Adie
Guest





PostPosted: Wed Jun 25, 2003 7:35 pm    Post subject: Re: virtual methods ? Reply with quote

Corey Murtagh wrote:
Quote:
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 :-)

Quote:
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?

Back to top
Corey Murtagh
Guest





PostPosted: Wed Jun 25, 2003 11:30 pm    Post subject: Re: virtual methods ? Reply with quote

Adie wrote:

Quote:
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.

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

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.

Quote:
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!"


Back to top
Robert Groves
Guest





PostPosted: Thu Jun 26, 2003 12:52 am    Post subject: Re: virtual methods ? Reply with quote

On Wed, 25 Jun 2003 18:32:17 +0100, Adie <a_usenetizen (AT) hotmail (DOT) com>
wrote:

Quote:
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[i];
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.

Back to top
Thomas Tutone
Guest





PostPosted: Thu Jun 26, 2003 1:28 am    Post subject: Re: virtual methods ? Reply with quote


"Adie" <a_usenetizen (AT) hotmail (DOT) com> wrote

Quote:
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[i];
newBase->f();

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

Quote:
}

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





Back to top
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ language (comp.lang.c++) All times are GMT
Goto page 1, 2  Next
Page 1 of 2

 
 


Powered by phpBB © 2001, 2006 phpBB Group