Click to See Complete Forum and Search --> : overriding base methods


ranadhir27
January 24th, 2002, 10:09 PM
i have a compilation problem in the following sample
testvirutal.h
-------------
#include "stdio.h"
class B{
public:
B(int i){xnt=i; printf("entered constructor B\n");}
int returnol(){return xnt;}
protected:
int xnt;

};
class D:public B{
public:
D(int i):B(i){printf("entered constructor D\n");};
using B::returnol;
char* returnol(char* p){return p;}
};
testmain.cpp
=============
#include "testvirtual.h"
void main()
{
D d(10);
D* sd=&d;
int ret;
char* r="dsgdg";
char* q;
q=sd->returnol(r);
ret=sd->returnol();
}
the error is
testvirtual.h:17: cannot adjust access to `int B::returnol()' in `class D'
testvirtual.h:16: because of local method `char * D::returnol(char *)' with same name

I thought that 'using' keyword should unhide the base method.what's the problem?

Tim Tsui
January 24th, 2002, 10:38 PM
The problem is int and pointer( no matter to what type ) is compliant types.

According this , the compiler cannot ajust which method you call , when you call returno1;

Another problem is ,
it is necessary to make B's destructor virtual

ranadhir27
January 24th, 2002, 11:33 PM
I have tried by changing the data types to long and string too.But I get the same error message.is there some other way to 'unhide' the base method?

Tim Tsui
January 25th, 2002, 12:34 AM
What compiler are you using ?
I am using gcc ,
there is no errors.

NMTop40
January 25th, 2002, 05:41 AM
that is overloading, not overriding.

Overriding means you have a virtual base function for which the derived class writes its own implementation.

Overloading means that the derived class writes a new function with the same name. This is done either when the base class method is non-virtual or when the derived class method has a different prototype (i.e. parameters and/or return type), or both.

There is one restriction - you cannot override (or attempt to overload) a virtual base function only by changing its return type.

For overloaded functions, like you have there, you can invoke the base-class function of the same name by scoping it, thus Base::function1()
from within the derived class or (<static_cast>(Base *)p)->function1() from outside. (cast to Base & if you have a ref/instance rather than a pointer).

Thus


class Base
{
public:
int function1( void *);
int function2( int );
};

class Derived : public Base
{
public:
void *function1( int )
{
int x = Base::function1( NULL );
return NULL;
}
void function2();
};

void main()
{
Derived o;
o.function1( 23 ); // ok
Base& br = o;
br.function2( 23 );
o.function2();
}







The best things come to those who rate