473,569 Members | 2,762 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 #1
20 1992

Daniel wrote:
The above program prints the following:

B::f()

But, I wanted the program to print

C::f()


prints "C::f()" over here. That is what it should do.

Feb 27 '06 #2

"Daniel" <da***********@ gmail.com> schrieb im Newsbeitrag
news:11******** **************@ v46g2000cwv.goo glegroups.com.. .
class C: public B
{
public:
void f();
};


you miss a virtual there.

f~
Feb 27 '06 #3

"Frank Schmidt" <fs@example.com > wrote in message
news:dt******** **@online.de...
|
| "Daniel" <da***********@ gmail.com> schrieb im Newsbeitrag
| news:11******** **************@ v46g2000cwv.goo glegroups.com.. .
|
| > class C: public B
| > {
| > public:
| > void f();
| > };
|
| you miss a virtual there.
|
| f~
|

Nope, if the pure-abstract or base class specifies that void f() is virtual
then its virtual in the entire hierarchy. Regardless whether the derived
classes have that function as virtual or not.

Feb 27 '06 #4

Peter_Julian wrote:
"Frank Schmidt" <fs@example.com > wrote in message
news:dt******** **@online.de...
|
| "Daniel" <da***********@ gmail.com> schrieb im Newsbeitrag
| news:11******** **************@ v46g2000cwv.goo glegroups.com.. .
|
| > class C: public B
| > {
| > public:
| > void f();
| > };
|
| you miss a virtual there.
|
| f~
|

Nope, if the pure-abstract or base class specifies that void f() is virtual
then its virtual in the entire hierarchy. Regardless whether the derived
classes have that function as virtual or not.


I thought it stopped at C meaning that any subclass of C would not be
able to polymorphically override f().

Feb 27 '06 #5

"Daniel" <da***********@ gmail.com> wrote in message
news:11******** **************@ v46g2000cwv.goo glegroups.com.. .
| I have the following three classes
|
| class A
| {
| public:
| virtual void f() = 0;
| };

undefined behaviour.
1) you failed to invoke delete x
2) In main() you are using a base pointer to a derived object and yet you
have not declared a virtual destructor in class A.

#include <iostream>
#include <ostream>

class A
{
public:
virtual ~A() { std::cout << "~A()\n"; }
virtual void f() = 0;
};

<snip>

|
| main()

int main()

| {
| A* x = new C();

A* x = new C;

|
| x->f();

delete x;

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

Your compiler is invoking the C() ctor correctly(which requires that both
A() and B() get allocated first) and then drops the allocation of the
derived C as if it were a temporary (which is not appropriate but otherwise
not strictly enforced). The remnant is a valid B-type object.

That should be fixed with the correct statement:
A* x = new C; // correctly invokes the default ctor to completion

Note that your problem, other than not using delete x at all (shame), has a
much more critical issue than the one you raise. If you don't provide a
virtual d~tor in class A then ~B() or ~C() will never be invoked. Thats a
guarenteed memory leak.

Test it:

int main()
{
A* x = new C;

x->f();

delete x;

return 0;
}

/* correct output
C::f()
~C()
~B()
~A()
*/

but what you are getting with the compiler generated d~tor(s) is:

C::f()
~A()

which is a partial destruction and a memory leak. bad news.

Moral of the story:

a) never, ever new if you don't delete
b) never, ever new[] if you don't [] delete
c)if you derive and destroy via a pointer to base:
***always provide a virtual d~tor***
or suffer the consequences.

Feb 27 '06 #6

<ro**********@g mail.com> wrote in message
news:11******** **************@ z34g2000cwc.goo glegroups.com.. .
|
| Peter_Julian wrote:
| > "Frank Schmidt" <fs@example.com > wrote in message
| > news:dt******** **@online.de...
| > |
| > | "Daniel" <da***********@ gmail.com> schrieb im Newsbeitrag
| > | news:11******** **************@ v46g2000cwv.goo glegroups.com.. .
| > |
| > | > class C: public B
| > | > {
| > | > public:
| > | > void f();
| > | > };
| > |
| > | you miss a virtual there.
| > |
| > | f~
| > |
| >
| > Nope, if the pure-abstract or base class specifies that void f() is
virtual
| > then its virtual in the entire hierarchy. Regardless whether the derived
| > classes have that function as virtual or not.
|
| I thought it stopped at C meaning that any subclass of C would not be
| able to polymorphically override f().
|

That doesn't make sense, and with good reason. The is_a relationship is
critical here. If you publicly derive from C and declare D, then its implied
that the D-type is_a C-type as well. You can perfectly well derive like
so...

class D : public C
{
};

and never declare void f() since a call like so...

A* p_a = new D;
p_a->f(); // will call C::f(), no problem - its expected
delete p_a; // invokes 4 d~tors - ~D, ~C, ~B and ~A

If there was a way to prevent the inheritance of a pure-virtual member
function, polymorphism would be broken. And there is...
___
The answer to your quest is simple: composition or private inheritance.
Sometimes its more important to understand when not_to_use polymorphic
inheritance.
Neither of these represent an "is_a" inheritance scheme.

class D
{
C c;
public:
void f() { } // not virtual
};

or D in_terms_of C, where D is_not C or B or A. This is also a form of
composition, not polymorphic inheritance...

class D : private C
{
void f() { std::cout << "D::f()\n"; } // not virtual
};

int main()
{
D d;
d.f();
}

/*
D::f() // not virtual
~D()
~C()
~B()
~A()
*/

Feb 27 '06 #7
Daniel wrote:
The above program prints the following:

B::f()


You must have made a copying error: the program does not compile
for me. There are missing include statements, namespace qualification,
and a missing return type of 'main()'. Once I fixed these problems,
the program prints "C::f()", as it should.
--
<mailto:di***** ******@yahoo.co m> <http://www.dietmar-kuehl.de/>
<http://www.eai-systems.com> - Efficient Artificial Intelligence
Feb 27 '06 #8

"Peter_Juli an" <pj@antispam.co digo.ca> schrieb im Newsbeitrag
news:fN******** ***********@new s20.bellglobal. com...

"Frank Schmidt" <fs@example.com > wrote in message
news:dt******** **@online.de...
|
| "Daniel" <da***********@ gmail.com> schrieb im Newsbeitrag
| news:11******** **************@ v46g2000cwv.goo glegroups.com.. .
|
| > class C: public B
| > {
| > public:
| > void f();
| > };
|
| you miss a virtual there.
|
| f~
|

Nope, if the pure-abstract or base class specifies that void f() is
virtual
then its virtual in the entire hierarchy. Regardless whether the derived
classes have that function as virtual or not.


say that to a compiler, which calls B::f() with the given the source
Feb 27 '06 #9

Peter_Julian wrote:
<ro**********@g mail.com> wrote in message
news:11******** **************@ z34g2000cwc.goo glegroups.com.. .
|
| Peter_Julian wrote:
| > "Frank Schmidt" <fs@example.com > wrote in message
| > news:dt******** **@online.de...
| > |
| > | "Daniel" <da***********@ gmail.com> schrieb im Newsbeitrag
| > | news:11******** **************@ v46g2000cwv.goo glegroups.com.. .
| > |
| > | > class C: public B
| > | > {
| > | > public:
| > | > void f();
| > | > };
| > |
| > | you miss a virtual there.
| > |
| > | f~
| > |
| >
| > Nope, if the pure-abstract or base class specifies that void f() is
virtual
| > then its virtual in the entire hierarchy. Regardless whether the derived
| > classes have that function as virtual or not.
|
| I thought it stopped at C meaning that any subclass of C would not be
| able to polymorphically override f().
|

That doesn't make sense, and with good reason. The is_a relationship is
critical here. If you publicly derive from C and declare D, then its implied
that the D-type is_a C-type as well. You can perfectly well derive like
so...

class D : public C
{
};

and never declare void f() since a call like so...


You totally missed my point. Doesn't matter because I was wrong but
still, I said one thing and you went off in a totally different
direction.

Feb 27 '06 #10

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

Similar topics

20
1756
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,...
3
1624
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
1898
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
4484
by: Adrian Herscu | last post by:
Hi all, In which circumstances it is appropriate to declare methods as non-virtual? Thanx, Adrian.
4
2210
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
2521
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....
2
1838
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
2104
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...
4
6561
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...
0
7609
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...
0
7921
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. ...
0
8118
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...
0
7964
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...
0
6278
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...
0
3651
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2107
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
1
1208
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
936
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...

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.