473,699 Members | 2,838 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Virtual Methods Question

I have the following three classes

class A
{
public:
virtual void f() = 0;
};

class B: public A
{
public:
virtual void f();
};

void B::f()
{
cout << "B::f()";
}

class C: public B
{
public:
void f();
};

void C::f()
{
cout << "C::f()";
}
main()
{
A* x = new C();

x->f();
}

The above program prints the following:

B::f()

But, I wanted the program to print

C::f()

Why is the program doing this? Is there any way for me to have C's f()
method invoked instead of B's f() method? I am using the GNU compiler
for VxWorks 5.5. Thanks in advance for any help.
-Daniel

Feb 27 '06
20 2003

"Jay_Nabonn e" <jn******@pacbe llo.net> wrote in message
news:pa******** *************** *****@pacbello. net...
| On Sun, 05 Mar 2006 02:11:19 -0500, Peter_Julian wrote:
|
| One more thought...
|
| >
| > Every cycle through the above program will leak memory since delete p
was
| > never called to invoke C's d~tor (of course, debug mode may help
depending
| > on your debugger). If you still don't think thats undefined behaviour:
write
| > a function that leaks a new allocation and loop through it a few
thousand
| > times in release mode.
| >
| > Anything could happen, it may format your hard drive, it might crash
your
| > OS, it may do nothing else except lower your resources. That, in effect,
is
| > the definition of undefined behaviour.
|
| Consider the following code:
|
| #include <list>
|
| typedef std::list<unsig ned char*> MyList;
|
| int main()
| {
| MyList l;
|
| // Allocate the world.
| try
| {
| for (;;)
| {
| l.push_back(new unsigned char[1024]);
| }
| }
| catch(...)
| {
| }
|
| // Release the world.
| for (MyList::iterat or i = l.begin(); i != l.end(); ++i)
| {
| delete [] *l;
| }
| }
|
| This code will (in theory) use up a tremendous amount of memory, only
| stopping when it is no longer able to allocate memory. Following the logic
| you expressed above, since it's unclear what the OS will do when it gets
| low on memory, then the above code exhibits "undefined behavior" (I'm
| setting up the same conditions, more or less, that the offending
| non-delete code had). It could, according to you, format the hard drive.

Not..

A computer that appropriately allocates and deallocates *all* of its memory
is low in resources at that very moment, thats all. Your arguement is not
the same. There is a huge difference between a program that runs out of
allocation space and one that permanently leaks it. The former renders a
known machine state and the latter does not.

As you've found out, the try block unwinds the stack only. That try block,
and much less a program, is unable to recover from a memory leak if you do
not deallocate the elements (the pointers would be lost forever).
Once the pointers are lost, no deallocation is possible unless you implement
placement new and an allocation pool (which is what debug mode does).

Or do i need to remind you that deallocating the pointer itself from the
stack does not deallocate the newed pointee?

Let me artificially induce a simulated memory allocation failure for you
after the tenth allocation.
Go ahead, comment out the %deallocations% section and then explain to me how
thats not undefined behaviour. That, after all, has been your arguement
until now.
____
#include <iostream>
#include <ostream>
#include <vector>
#include <list>
#include <stdexcept>

class N
{
int m_n;
std::vector<int > vn;
public:
N(int n) : m_n(n), vn(1024, 0)
{
if (m_n > 9) throw std::bad_alloc( "out of mem !!!");
std::cout << "\nN()";
}
~N() { std::cout << "\n~N()"; }
};

int main()
{
std::list< N* > ln;
try
{
// allocations
for (int i = 0;; ++i)
{
ln.push_back(ne w N(i));
}
}
catch (const std::exception& e)
{
std::cout << "\nerror: " << e.what();
}

// size()
std::cout << "\n# of elements in list = " << ln.size();

// deallocations
typedef std::list< N* >::iterator LIter;
LIter liter = ln.begin();
for( liter; liter != ln.end(); ++liter)
{
delete *liter;
}

return 0;
}

/*

N()
N()
N()
N()
N()
N()
N()
N()
N()
N()
error: out of mem !!!
# of elements in list = 10
~N()
~N()
~N()
~N()
~N()
~N()
~N()
~N()
~N()
~N()

*/
____

|
| And yet (assuming I coded it right off the top of my head) all new's are
| paired with delete's. So how to identify the "undefined behavior"?

The program does not produce undefined behaviour since deallocation takes
place. You answered your own question. However, you've missed a critical
point... what if class N was a derived class?

Yes, thats right, what if we didn't modify main() in any way and derived
from a base class? hmm?

|
| Again, even though the effect of the above code on an OS is not
| necessarily predictable, it is not "undefined behavior" as defined by the
| C++ standard. So the effect of a memory leak on the OS is immaterial since
| the above code, which has no undefined behavior as defined by the C++ spec
| duplicates the conditions you described.
|
| - Jay
|

Thats not so, the programs you have described until now are ones without
deallocations. This program does not leak resources. Thanks, but you've
basicly proven the point i was making.

Now, lets start dealing with the real issue: shall we? I like to stick to my
guns.

If class N above were a derived class and its base class did not have a
virtual d~tor, deallocating the class N elements would leak the base class
component at each iteration. That's the undefined behaviour i was alluding
to.

Try it! add a base class with a non-virtual destructor, derive class N from
it, and test the theory with output in the base class d~tors. Pay attention.
I'm talking of a derived N *with* deallocation.

Hmm, undefined behaviour takes a whole new meaning then, doesn't it? delete
pointer is incapable of invoking the base class d~tor unless its virtual.
Thats a fact that needs to be viewed with great respect in C++ since
debugging for it when the client calls is a nightmare.

That is why, for example, deriving from the STL containers is not
recommended. Their destructors are not virtual.
Ya learn something every day, thats what makes life cool.

Mar 7 '06 #21

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

Similar topics

20
1774
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 Perforamce Tips and Tricks in .NET Applications, A .Net Developer Platform White Paper, at the very bottom, it says: The JIT cannot inline virtual methods, so you lose a potential optimization if you get rid of non-virtual methods.
3
1626
by: Milan Cermak | last post by:
Hi all, I have sort of philosophical question. Contructor and destructor behavior points me to this. Is table of virtual methods held in object? Do I get it right that every created object has its own table of virtual methods? Even if they are of one class? Thanks for reactions, Milan Cermak
9
1904
by: jlopes | last post by:
There seems to bet no diff between a vitual method and an inheirited method. class A_Base { public: virtual void filter(){ /* some code */ } }; class D_of_A_Base : public A_Base {
4
385
by: aap | last post by:
Hi, I have the following code. #include <iostream> using namespace std; class Root { public: virtual void Root1() = 0; virtual void Root2() = 0;
32
4512
by: Adrian Herscu | last post by:
Hi all, In which circumstances it is appropriate to declare methods as non-virtual? Thanx, Adrian.
4
2217
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 bool Equals(object obj) {} Another is using the override keyword, like: public override bool Equals(object obj) {}
15
2545
by: John Salerno | last post by:
Hi all. I have a question about virtual and override methods. Please forgive the elementary nature! First off, let me quote Programming in the Key of C#: "Any virtual method overridden with 'override' remains a virtual method for further descendent classes." Now here's my question: Let's say you have base class A, and subclasses B and C. Class A contains a virtual method, and B contains an override method. If C didn't have an...
2
1863
by: Heinz Ketchup | last post by:
Hello, I'm looking to bounce ideas off of anyone, since mainly the idea of using Multiple Virtual Inheritance seems rather nutty. I chalk it up to my lack of C++ Experience. Here is my scenario... I have 5 Derived Classes I have 3 Base Classes
7
2111
by: Markus Svilans | last post by:
Hello, My question involves virtual functions and inheritance. Suppose we have a class structure, that consists of "data" classes, and "processor" classes. The data classes are derived from BufferBase, and customized in order to be able to a type of data (of any kind, such as chunks of audio samples from a sound card). The processor classes are derived from ProcessorBase, and are customized to handle BufferBase-derived objects. Each...
4
6567
by: David Zha0 | last post by:
Hi, "when we call a virtual method, the runtime will check the instance who called the method and then choose the suitable override method, this may causes the performance drop down", is this right? And, why not use "new" instead of using "virtual"? And the last question, what is the differences between a abstract method and a interface?
0
8685
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
8612
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
9171
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8905
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
8880
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
7743
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5869
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
4625
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3053
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.