SRL Archive - C/C++ Help and Tutorials

virtual Question.


Macro_FTW

2009-08-14 19:11:48

[[[EDIT]]] I have my answer (B.) Thanks. :) [[[/EDIT]]]

Hello all.

Just a quick question on how virtual works in C++.

Say I had code like this:

//Includes are assumed
class Base {
public:
virtual char getChar() { return 'a'; }
char sayChar() { cout << getChar(); }
};

class Adv: public Base {
public:
char getChar() { return 'b'; }
};

void main() {
Adv a;
cout << a.sayChar();
}

Will that print out 'a', or 'b'?

In other terms, I'm asking if a virtual method is declared and used in a superclass, but the same method is overwritten in the subclass, will the subclass' method be used in any superclass-only method calls for it?

Thanks!
~Macro_FTW

boberman

2009-08-23 03:39:50

It will print out b. When you define a virtual class its like saying "If no function is defined, do this".

Whats more fun is when you say something like

void saySomething(Base a)
{
cout << a.sayChar;
}

int main()
{
Adv a;
saySomething(a);
}

In this case it will say a, not b. (Confusing I know). In order to make it say b instead you have to pass it in by reference or as a pointer.