| re: virtual function problem
foodic wrote:
[color=blue]
> Hi all,
> I am new to c++ I have a problem compiling this program,
>
> #include <iostream.h>[/color]
Note that <iostream.h> is an obsolete non-standard header that should be
avoided. Use <iostream> instead.
[color=blue]
> class iq
> {
> protected :
> int k;
> public :
> iq(int k){
> this->k=k;
> }[/color]
Better use initialization instead of assignment. For built-in types like
int, it doesn't make much of a difference, but for class types, it does. So
write:
iq(int k)
: k(k)
{
}
And though it's possible to have the same name for the parameter as for the
member variable, the code is usually considered more readable if they have
different names.
[color=blue]
> virtual void printiq(){}
> };
> class im : public iq
> {
> int l;
> public :
> im(int k):iq(k) {
> this->l=k;
> }
> void printiq(){
> cout <<l;
> }
>
> };
> int main(){
> im l(10);
> iq *l;
> ((l)iq*)->printiq();
> }
> Basically I want to acess the derived class member function
> through pointer to the Base class. When i compile this program
> it gives error like,
> inherit.c: In function `int main ()':
> inherit.c:26: conflicting types for `iq *l'
> inherit.c:25: previous declaration as `im l'[/color]
The compiler says it quite clearly. You're trying to declare two variables
of different type (one of type im, the other of type pointer to iq) that
have the same name.
[color=blue]
> inherit.c:27: parse error before `*'[/color]
What is ((l)iq*) supposed to do? It looks kind of like a C style cast, but
with type and value swapped. That doesn't make sense, neither to me, nor to
the compiler. ;-)
And if it was supposed to be a cast, drop it. You don't need one here.
[color=blue]
> How to solve this problem,[/color]
Give your variables different names:
int main(){
im l(10);
iq *m = &l;
m->printiq();
} |