473,804 Members | 2,124 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help me understand Overriding a virtual function

I read that the return type has to be exactly same for a virtual
function to be overriden. While testing something, I discovered
something I cannot understand.
I cannot understand why the code below compiles.

I see that it won't compile if I have "virtual char & vtest() { }" in
Base class
and have "virtual const char & vtest() { }" in Derived class.

But it compiles if I have "virtual const char & vtest() { }" in Base
class and have "virtual char & vtest() { }" in derived class.
Why? What's going on?

Similarly, operator*() functions compiles as written, but always
returns const int & even I assign derived object to Base reference.
Please have a look at comments on function fun() to see what I mean.

Can anyone kindly explain why it compiles yet won't do dynamic
binding?
Thanks always (especially to you, Victor B.)

#include <iostream>
using std::cout;
using std::endl;

class CPtr {
public:
CPtr(int * a):ptr(a) { };
virtual const int & operator*() const
{
return *ptr;
}
virtual const char & vtest() { }
protected:
int * ptr;
};

class Ptr: public CPtr {
public:
Ptr(int * a):CPtr(a) { };
virtual int & operator*() const
{
return *ptr;
}
virtual char & ttest() { }
};

void fun(CPtr & p)
{
// I was hoping this would work since a Ptr object is passed and
// dynamically it would bind to virtual int & operator*() const
// But it binds to virtual const int & operator*() const at compile
time
// Why?

// cout << ++(*p) << endl;
}

int main()
{
int i = 10;
Ptr pt(&i);
cout << ++(*pt) << endl;
fun(pt);

return 0;
}
Jul 22 '05 #1
3 2183

"CoolPint" <co******@yahoo .co.uk> wrote in message
news:15******** *************** **@posting.goog le.com...
I read that the return type has to be exactly same for a virtual
function to be overriden. While testing something, I discovered
something I cannot understand.
I cannot understand why the code below compiles.

I see that it won't compile if I have "virtual char & vtest() { }" in
Base class
and have "virtual const char & vtest() { }" in Derived class.

Because if it did you could violate const correctness.
But it compiles if I have "virtual const char & vtest() { }" in Base
class and have "virtual char & vtest() { }" in derived class.
Why? What's going on?
Because with this you can't:
A CPtr will return you a cont reference whether or not it is actually a Ptr.

Similarly, operator*() functions compiles as written, but always
returns const int & even I assign derived object to Base reference.
Please have a look at comments on function fun() to see what I mean.

Can anyone kindly explain why it compiles yet won't do dynamic
binding?
Thanks always (especially to you, Victor B.)

#include <iostream>
using std::cout;
using std::endl;

class CPtr {
public:
CPtr(int * a):ptr(a) { };
This is the start of your misconceptions:
If CPtr is a pointer to a const int then why doesn't it take one ine the
constructor?
Your CPtr cannot actually point to a constant integer!
If you change to CPtr(const int*) the problems that you will then have with
Ptr(int*) should show you
why your design is flawed and why C++ works the way it does.
virtual const int & operator*() const
{
return *ptr;
}
virtual const char & vtest() { }
returns what?
protected:
int * ptr;
};

class Ptr: public CPtr {
inheritance is not appropriate here.
You are saying "Every Ptr IS-A CPtr"
or "every pointer is a pointer to constant except that you can change it!"
This is obviously nonsensical.
public:
Ptr(int * a):CPtr(a) { };
If you had CPtr(const int*) you would not now be able to initialize it with
a.
virtual int & operator*() const
{
return *ptr;
}
virtual char & ttest() { }
};

void fun(CPtr & p)
{
// I was hoping this would work since a Ptr object is passed and
// dynamically it would bind to virtual int & operator*() const
// But it binds to virtual const int & operator*() const at compile
time
No it doesn't - it binds to virtual int& operator*() (look at the asembler)
BUT the the return type is treated as const int& because that is what it is
in CPtr.

C++ uses dynamic function calls but static type checking.
Or to put it another way virtual function calls select functions at runtime
NOT types.
// Why?

// cout << ++(*p) << endl;
}

int main()
{
int i = 10;
Ptr pt(&i);
cout << ++(*pt) << endl;
fun(pt);

return 0;
}

Jul 22 '05 #2
> No it doesn't - it binds to virtual int& operator*() (look at the asembler)
BUT the the return type is treated as const int& because that is what it is
in CPtr.

C++ uses dynamic function calls but static type checking.
Or to put it another way virtual function calls select functions at runtime
NOT types.


Does that mean return types of virtual functions do not take part in
the resolving of dynamic binding?

Thank you for your comments. The coding was made just to illustrate
the points I am trying to ask in simple way without considering the
design. What I really want to find out is the feature of the langauge
and how it works and you kind of answered above there but it's not
clear to me yet. Could you kindly elaborate a bit more?

Books say the return type has to be exactly same when a virtual
function is overriden but why doesn't compiler complain in the
following case:

Base member's return type : virtual const T &
Derived member's return type : virtual T &

They look different types to me but compiler doesn't complain. But
compiler complains when the situation is reversed though.

Does this mean I have successfully overridden the function for dynamic
binding to work? If then, why calling the member function through base
reference would return the base class member's return type?

Thank you for your patience.
Jul 22 '05 #3

"CoolPint" <co******@yahoo .co.uk> wrote in message news:15******** *************** ***@posting.goo gle.com...
Does that mean return types of virtual functions do not take part in
the resolving of dynamic binding?
Correct. The important issue is name and parameter list. However,
the return types of overriding functions are required to be same or one
of the legal related types.
Books say the return type has to be exactly same when a virtual
function is overriden but why doesn't compiler complain in the
following case:


Those books are wrong. The rule is relaxed in the case when:
1. Both returns are pointers or references to classes
2. The type of the base class function return is an unambiguous accessible base class
of the return of the derived class function
3. The CV-qualification is the same for the pointers, and the same or less qualfifed for
the pointed/referred to derived object

Jul 22 '05 #4

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

Similar topics

5
2731
by: Hongzheng Wang | last post by:
Hi, I have a problem about the overriding of private methods of base class. That is, if a method f() of base class is private, can the derived class overriding f() be overriding? For example, class base {
8
2851
by: JustSomeGuy | last post by:
I need to write an new class derived from the list class. This class stores data in the list to the disk if an object that is added to the list is over 1K in size. What methods of the std stl list class must Ioverride in order for this to work?
15
24015
by: Susan Baker | last post by:
Hello everybody, I'm new to C++ (I have some C background). I've read up on this topic a few times but it just dosen't seem to be sinking in. 1. Whats the difference between overloading and overriding? 2. When is one preferable to use as opposed to the other? 3. How are virtual functions related to this topic (overloading/overriding) - a real world example of using virtual functions would be very much appreciated.
11
1794
by: Achintya | last post by:
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& #include<iostream> using namespace std; class A { int i; virtual void f(){ cout<<endl<<"i= "<<i; } public: A(int j) { i = j; }
1
5852
by: paulsmith5 | last post by:
Hi, I've never developed in CSharp before and I'm trying to adapt an existing user control written in CSharp. The user control inherits from the DataGridColumn. I'd like for one of my controls properties to override that of the DataGridColumn. Could somebody help with the syntax? Currently my code for the property is as follows: public virtual string HeaderStyle {
3
8697
by: David Scarlett | last post by:
Hi all, I've got a question regarding overriding const member functions with non-const functions. Let's say I've got a base class defined as follows: /*******************/ class Foo { public:
13
5168
by: ctor | last post by:
Hi, I'm experiencing an annoying issue. Here is a simplified idea of what I am trying to do. Inclusion guards aren't shown for readability. I hope this isn't too confusing; I don't think a description would be as clear as an example. ----------- class ParentA {};
3
2027
by: Rick | last post by:
One of the rules I have recommended for our new coding standard is as follows: "When overriding a base class virtual function, all overloads of that base class virtual function should also be overridden. Otherwise, the overloads of the overridden function in the base class will not be visible from the derived class." In other words...
12
1559
by: danil52 | last post by:
Hello there, I have the following code: class Base { public: virtual void f() {cout << "Base::f()" << endl;} virtual void f(int) {cout << "Base::f(int)" << endl;} };
0
9715
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9595
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10353
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10356
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10099
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6869
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5675
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3836
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3003
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.