the virtual keyword

  • Thread starter Michael P. O'Connor
  • Start date
M

Michael P. O'Connor

it was my understanding that if you were to declare a function as virtual
you could not declare a body for it in the class it was declared virtual,
but playing around with it tonight, it let me do this. and with the
following code



class a
{
public: virtual void fun() {std::cout << "class a" << std::endl; };
};

class b : public class a
{
public: void fun() { std::cout << "class b" << std::endl; };
};

int main()
{
a aa;
b bb;
a *p;
p = &aa;
p->fun();
p = &bb;
p->fun();
return 0;
}

it printed out
class a
class b

my question is what is the benefits to this, what are the down falls to
this? I have a use for this ability but something tells me there is
something that I am overlooking and I might run into problems down the
road. So am I being paranoid?
 
S

Sowen

hi,

if you don't use virtual

then even u override the parent's method, when u

a obj = new b();
a->fun();

it will call the fun method in class a not class b

but, if u use virtual, it will cal the method in class b

i am not sure the benefits of it, but i know there are some unpleasure
results of this feature :)

so, remember to use virtual when u need polymorphism

--
Best Regards!
Sowen Cheung
http://com.angGoGo.com
http://www.angGoGo.com
http://biz.angGoGo.com
 
M

Michael P. O'Connor

I did see that when I ran the test program, and I have in a program I am
working a need for polymorphism in this case, I just want to know what the
downfalls might be, should I look at other options, if the problems out
weigh the benefits, so I just need to know the problems, so I can weigh
the options before I continue to far on.
 
G

GB

Michael said:
it was my understanding that if you were to declare a function as virtual
you could not declare a body for it in the class it was declared virtual,

That is not correct. It is ok to declare a member function virtual even
if you define it within the class definition. However, the implicit
inlining hint that occurs with functions defined within the class
definition will probably not actually result in inlining in this case.

Since virtual functions may be overridden, the actual function that gets
called at a specific point in your program must be determined at runtime
(typically by looking up its address in a table pointed to by a an
implementation-generated hidden field in the object). Only if the
compiler can determine which function to call at compile-time is
inlining usually a possibility. For example,

obj->func();

will result in a table lookup of the address of the function to call, so
it can't be inlined. On the other hand,

obj->Obj::func();

may be inlined since the compiler knows the specific function you are
trying to call.

Gregg
 
I

Ioannis Vranos

Michael said:
it was my understanding that if you were to declare a function as virtual
you could not declare a body for it in the class it was declared virtual,


Wrong understanding. virtual has nothing to do with definition styles.

but playing around with it tonight, it let me do this. and with the
following code



class a
{
public: virtual void fun() {std::cout << "class a" << std::endl; };
};

class b : public class a
{
public: void fun() { std::cout << "class b" << std::endl; };
};

int main()
{
a aa;
b bb;
a *p;
p = &aa;
p->fun();
p = &bb;
p->fun();
return 0;
}

it printed out
class a
class b

my question is what is the benefits to this, what are the down falls to
this?


Of what?

I have a use for this ability but something tells me there is
something that I am overlooking and I might run into problems down the
road. So am I being paranoid?


:)
 
M

Michael P. O'Connor

That is not correct. It is ok to declare a member function virtual even
if you define it within the class definition. However, the implicit
inlining hint that occurs with functions defined within the class
definition will probably not actually result in inlining in this case.

So what are the benefits of having the function virtual, and defined,
and what are the problems.

In such a case would it be better to define a new class that both the
original class and the one that would have derived from the original class
would derive from, or is it better to have the virtual function in
the original class with a definition, and overload it if needed in a
derived class? (oh man I hope I worded that question in a way people know
what I am asking)
 
I

Ioannis Vranos

Michael said:
I did see that when I ran the test program, and I have in a program I am
working a need for polymorphism in this case, I just want to know what the
downfalls might be, should I look at other options, if the problems out
weigh the benefits, so I just need to know the problems, so I can weigh
the options before I continue to far on.


Only use polymorphism when it makes sense. I will use an example from
..NET since it is a GUI environment that I know.


There a Form class is provided with its defaults, and when we want to
create a Form with buttons etc, we do something like:


class MyForm: public Form
{
Button *pOkButton;

// ...

public:
Myform()
{
// ...

pOkButton= new Button;

pOkButton->Text= "OK";

// ...
}
};


It doesn't make sense to use polymorphism here.


As a rule of thumb, don't use polymorphism unless you need it.
 
M

Michael P. O'Connor


that is my question is there down falls, and if so what are they, and as
to what, having a function virtual with a body, with the idea that it
could be overrides. Could it cause some problems for me that I am yet to
know about.
 
G

Gregg

So what are the benefits of having the function virtual, and defined,
and what are the problems.

The only practical reason I can think of for doing it would be to save
yourself the trouble of writing a separate cpp file for one or two
functions when everything else is already in the header.
In such a case would it be better to define a new class that both the
original class and the one that would have derived from the original
class would derive from, or is it better to have the virtual function
in the original class with a definition, and overload it if needed in
a derived class? (oh man I hope I worded that question in a way
people know what I am asking)

I'm sorry but I don't understand what you are asking here.

Gregg
 
M

Michael P. O'Connor

I'm sorry but I don't understand what you are asking here.

Gregg
Well your first answer, answered the second question, I don't think the
second question matters much any more.
 
I

Ioannis Vranos

Michael said:
that is my question is there down falls, and if so what are they, and as
to what, having a function virtual with a body, with the idea that it
could be overrides. Could it cause some problems for me that I am yet to
know about.


The only way that you may have a virtual member function "without a
body", that is without a definition, is if you make it abstract:


class SomeClass
{
public:
virtual void somefunc()=0;
};


This makes the class an abstract base class, and no instances can be
created of the class itself.


I think a good, slow, thorough read of an up to date ISO C++
introductory book, will benefit you the most, as is always the case.
 
S

Sowen

unfortunately, you are wrong

The reason virtual exists in C++ is so you can leave it off for a slight
increase in efficiency when you're tuning for performance (or, put another
way, "If you don't use it, you don't pay for it"), which often results in
confusion and unpleasant surprises.

Not actually what you point "without a body"

--
Best Regards!
Sowen Cheung
http://com.angGoGo.com
http://www.angGoGo.com
http://biz.angGoGo.com
 
M

Matthias Kaeppler

Sowen said:
unfortunately, you are wrong

The reason virtual exists in C++ is so you can leave it off for a slight
increase in efficiency when you're tuning for performance (or, put another
way, "If you don't use it, you don't pay for it"), which often results in
confusion and unpleasant surprises.

So, virtual exists for the sole purpose for not using it if you want
better performance? o_O
Is that what you're saying? Somewhat twisted logic. :)
 
S

Sowen

Actually, that's not from me, I just copied from the word of the author of
Thanking in C++. (forget his name, ^^)

If u don't understand this, the word from Stroustrup might help

"objects of a class with a virtual function require space needed by the
virtual function call mechanism - typically one word per object"

I guess this is one reason that virtual is not default, 'cause it's wasteful

Furthermore, I do agree the following

"Because many classes are not designed to be used as base classes. Virtual
functions make sense only in classes meant to act as interfaces to objects
of derived classes (typically allocated on a heap and accessed through
pointers or references). "

I am sorry, I said Mr.Ioannis was wrong in my last reply. Now I review his
reply, I think I misundertsand him before. His word is another way to state
a class is an abstract.


--
Best Regards!
Sowen Cheung
http://com.angGoGo.com
http://www.angGoGo.com
http://biz.angGoGo.com
 
I

Ioannis Vranos

Sowen said:
I am sorry, I said Mr.Ioannis was wrong in my last reply. Now I review his
reply, I think I misundertsand him before. His word is another way to state
a class is an abstract.


What I said is that a virtual method cannot be without a definition,
unless it is abstract.
 
A

Alex

it was my understanding that if you were to declare a function as virtual
you could not declare a body for it in the class it was declared virtual,

Then your understanding is wrong here. You can implement any method in a
class, unless it is defined as *pure virtual*. If you define a pure
virtual method, you get an abstract class, that will result in a compiler
error, when instanciated with the new keyword.

An abstract base class would be defined like this:

class a
{
public:
virtual void fun() = 0;
};

This class can only be used as a base class, calling

a* obj = new a;

would result in a compiler error. Any derived class *must* implement
a::fun()!

I think is that what you meant.
my question is what is the benefits to this, what are the down falls to
this? I have a use for this ability but something tells me there is
something that I am overlooking and I might run into problems down the
road. So am I being paranoid?

The benefit is of course, that you can inherit functions of base classes
through serveral levels of inheritance. If you define a class:

class c : public class b {
public:
void fun(void) { std::cout << "class c" << endl; };
};

this would work ok:

int main()
{
a aa;
c cc;
a *p;
p = &aa;
p->fun();
p = &cc;
p->fun();
return 0;
}

If you want to create more complex class-libraries, this would become very
handy. This only works if b::fun() is also virtual, otherwise the
inheritance chain would be broken, and the mechanism fail (c inherits
fun() from b, not from a!).
Internally the compiler represents a virtual function as a
function pointer that is added to the actual class. Even if the variable
an object is assigned to is of a base class, the pointer will be set to
the derived function, so you can call the derived function instead of that
of the base class.
The price for this is that each virtual function needs an additional
pointer size of memory. Plus the pointer has to be initiallized in the
beginning.
Usually the compiler handles all this for you, so you don't have to mess
with it. But you should keep this fact in mind, when you stream an object
at runtime, e.g. for sending it through a pipe.

BTW, as other posters mentioned before, your inline declararion would not
be compiled as actual inline code, because of the internal pointer
representation.

regards,
Alex
 
M

Matthias Kaeppler

Alex said:
Then your understanding is wrong here. You can implement any method in a
class, unless it is defined as *pure virtual*. If you define a pure
virtual method, you get an abstract class, that will result in a compiler
error, when instanciated with the new keyword.

It will also be a compiler error without the new keyword... ABCs can't
be instantiated, regardless which way.
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top