how overriding works

hi,
i've a small program

class A
{

public:
void GET()
{
cout<<" Inside A "<<endl;
}
};

class B : public b
{

public:
void GET()
{
cout<<" Inside B "<<endl;
}
};

int main()
{
B b;
b.GET();
}

if i run the above code it is giving me Inside B. But how can i call the Base class function. I made base class GET function as virtual after that also it is calling the derived class only. Can any one tell me how exactly it is working.

also can anyone tell how the overriding concept will work??

Thanks in advance..
There is nothing complex in this, you are creating B's object and its natural it will call B's function.
if you create A's object it will call A's function.

If you want the same object to call different functions make base function virtual.
virtual void GET();

now in main do this to call derived class function using base pointer:
1
2
B b;
A *a = &b;

or
A *a = new B;

to call Base function:
A *a = new A;

dont forget to delete the pointer's later.

to understand the details of how this is working read
Inside C++ object model by lippman
.
Non virtual functions of the same name are determined by the compile time type of the object calling them.
Virtual functions of the same name are determined by the run time type of the object calling them (ie, the real type).

In your example, 'b' is a B object, therefore B::GET is being called. If it were an A object, then it would be A::GET being called.

Here's a sample:

1
2
3
4
5
6
7
B b;
b.GET();  // "inside B"

// change the compile time type to 'A'
A* a = &b;
a->GET();  // "inside A" if the function is nonvirtual
           // or "inside B" if the function is virtual 


Because 'a' really is a B object (or rather, it points to a B object), if the function is virtual, the B::GET will be called because the object really is a B.

However, the compiler doesn't know that it's a B object at compile time. So if the function is nonvirtual, when it sees 'a->GET', it looks at the type that 'a' is. Since it looks to be A, it uses A::GET.


All that said. You generally don't want to call the parent class's function because it defeats the entire point of overriding the function. If you find yourself having to do this, you're probably better off creating separate functions with different names and avoiding the name conflict.

edit: bah I'm too slow ^^
Last edited on
thanks disch and sharma for the kind explanation...
You can also directly call a base function with something like this:
b.A::GET();
Topic archived. No new replies allowed.