Yet another inheritance question...

Started by
3 comments, last by Polymorphic OOP 19 years, 6 months ago
I am fiddling around while learning c++ inheritance, and produced the following test code:

#include <iostream>

class A{
void foo(){cout << "a";}
};

class B : public A{
public:
void foo(){cout << "b";}
};

void main(){

B b;
b.foo();
}

Which compiles nicely and prints b. I'd expected an error. Is this behavior reliable?
Advertisement
Quote:Original post by Telastyn
Is this behavior reliable?

It is the correct behavior according to the C++ standard.
Arguing on the internet is like running in the Special Olympics: Even if you win, you're still retarded.[How To Ask Questions|STL Programmer's Guide|Bjarne FAQ|C++ FAQ Lite|C++ Reference|MSDN]
Quote:Original post by Telastyn
I am fiddling around while learning c++ inheritance, and produced the following test code:

*** Source Snippet Removed ***

Which compiles nicely and prints b. I'd expected an error. Is this behavior reliable?


That should be std::cout << "a" and "b." As well, void main should be int main.

Once you change those problems, yes, that's standard code, and yes, that is the output you should be getting.
This is expected and reliable. Next comes the fun part.

#include <iostream>class A{void foo(){cout << "a";}};class B : public A{public:void foo(){cout << "b";}};void test(A &a){  a.foo();}void main(){B b;b.foo();test(b);}


What will test(b) print? It will print "a" because the compiler sees an object of class A when it compiles the test() function, so it calls A's version of foo(). But what if you want the compiler to "know" what kind of object you passed it, and call B's function? You make the foo function virtual.

#include <iostream>class A{virtual void foo(){cout << "a";}};class B : public A{public:virtual void foo(){cout << "b";}};void test(A &a){  a.foo();}void main(){B b;b.foo();test(b);}


In this case the compiler creates a table of function pointers (called a vtable) for each class. When test() calls a.foo(), it looks at the object's vtable, which is actually B's vtable, and uses the function pointer it finds in there (so it calls B's version of foo()).
Quote:Original post by s_p_oneil
In this case the compiler creates a table of function pointers (called a vtable) for each class. When test() calls a.foo(), it looks at the object's vtable, which is actually B's vtable, and uses the function pointer it finds in there (so it calls B's version of foo()).

It is important to note that a compiler does not have to use a vtable and those that do don't have to use the same layout. The C++ standard never guarantees an implementation of polymorphism. vtables are, however, the most common implementation.

This topic is closed to new replies.

Advertisement