473,396 Members | 2,158 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

the virtual keyword

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?
Jul 23 '05 #1
16 1687
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
"Michael P. O'Connor" <mp**@mikeoconnor.net> wrote in message
news:pa****************************@mikeoconnor.ne t...
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?

Jul 23 '05 #2
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.
Jul 23 '05 #3
GB
Michael P. O'Connor wrote:
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
Jul 23 '05 #4
On Sat, 05 Mar 2005 01:39:57 -0500, GB wrote:
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)
Jul 23 '05 #5
Michael P. O'Connor wrote:
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?

:-)

--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 23 '05 #6
On Sat, 05 Mar 2005 08:46:40 +0200, Ioannis Vranos wrote:
my question is what is the benefits to this, what are the down falls to
this?

Of what?


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.
Jul 23 '05 #7
Michael P. O'Connor wrote:
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.


--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 23 '05 #8
"Michael P. O'Connor" <mp**@mikeoconnor.net> wrote in
news:pa****************************@mikeoconnor.ne t:
On Sat, 05 Mar 2005 01:39:57 -0500, GB wrote:
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.


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

Jul 23 '05 #9
On Sat, 05 Mar 2005 06:56:39 +0000, Gregg wrote:
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.
Jul 23 '05 #10
Michael P. O'Connor wrote:
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.

--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 23 '05 #11
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
"Ioannis Vranos" <iv*@remove.this.grad.com> wrote in message
news:1110009979.365695@athnrd02...
Michael P. O'Connor wrote:
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.

--
Ioannis Vranos

http://www23.brinkster.com/noicys

Jul 23 '05 #12
Sowen wrote:
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. :)

--
Matthias Kaeppler
Jul 23 '05 #13
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
"Matthias Kaeppler" <no****@digitalraid.com> wrote in message
news:d0*************@news.t-online.com...
Sowen wrote:
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. :)

--
Matthias Kaeppler

Jul 23 '05 #14
Sowen wrote:
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.

--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 23 '05 #15
On Sat, 05 Mar 2005 01:05:50 -0500, Michael P. O'Connor wrote:
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
Jul 23 '05 #16
Alex wrote:
On Sat, 05 Mar 2005 01:05:50 -0500, Michael P. O'Connor wrote:

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.


It will also be a compiler error without the new keyword... ABCs can't
be instantiated, regardless which way.
--
Matthias Kaeppler
Jul 23 '05 #17

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

20
by: Raymond Lewallen | last post by:
I read this on this website page http://www.vbip.com/books/1861004915/chapter_4915_06.asp: Unlike many object-oriented languages, all methods in VB.NET are virtual. Now in BOL, Under...
24
by: Shao Zhang | last post by:
Hi, I am not sure if the virtual keyword for the derived classes are required given that the base class already declares it virtual. class A { public: virtual ~A();
7
by: qazmlp | last post by:
When a member function is declared as virtual in the base class, the derived class versions of it are always treated as virtual. I am just wondering, why the same concept was not used for the...
12
by: Daniel Kay | last post by:
Hi Folks! Everytime I work with virtual and pure virtual methods I ask myself if there is a difference between class B and class C (see below). Is it redundant to repeat the virtual keyword in a...
5
by: gouqizi.lvcha | last post by:
Hi, all: I have 3 class X, Y, Z class Y is a subclass of class X; class Z is a subclass of class Y; i.e. class Y : public class X class Z : public class Y
32
by: Adrian Herscu | last post by:
Hi all, In which circumstances it is appropriate to declare methods as non-virtual? Thanx, Adrian.
4
by: Rafael Veronezi | last post by:
I have some questions about override in inheritance, and virtual members. I know that you can you override a method by two ways in C#, one, is overriding with the new keyword, like: public new...
14
by: JPRoot | last post by:
Hi I use the following syntax to have events inherited from base to child classes which works nicely (virtual and override keyword on events). But I am wondering if it is a "supported" way of using...
8
by: JPRoot | last post by:
Hi M. Jeffrey Tan, Just hopping you didn't forget me? :) Thanks JPRoot ----- \"Jeffrey Tan\" wrote: -----
5
by: Marcel Hug | last post by:
Hi NG ! I'm new in C# and I'm reading a book about the fundamentals and concepts. In the chapter Methods it's written to use virtual, if i would like to override the method in a subclass. This...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.