|
-
January 24th, 2002, 11:09 PM
#1
overriding base methods
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 ublic 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?
-
January 24th, 2002, 11:38 PM
#2
Re: overriding base methods
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
-
January 25th, 2002, 12:33 AM
#3
Re: overriding base methods
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?
-
January 25th, 2002, 01:34 AM
#4
Re: overriding base methods
What compiler are you using ?
I am using gcc ,
there is no errors.
-
January 25th, 2002, 06:41 AM
#5
Re: overriding base methods
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
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|