#include<iostream>
class base
{
public:
int get();
int put();
};
class Derive: public base
{
public:
int get();
int put();
};
int base::get()
{
int x = 5;
return x;
}
int base::put()
{
int y = 10;
return y;
}
int Derive::get()
{
int a = 9;
return a;
}
int Derive::put()
{
int b = 20;
return b;
}
int main()
{
Derive d;
d.get(); // this line will return 9 according to class how can I
get 5 from here (base class method get();)
return 0;
}
How can I call base class method from derive class object without
using virtual.
> int main()
> {
> Derive d;
> d.get(); // this line will return 9 according to class how can I
> get 5 from here (base class method get();)
>
> return 0;
> }
>
> How can I call base class method from derive class object without
> using virtual.
Actually, virtual functions and polymorphy work precisely the other way round.
To answer your question, you can do two things: (1) specify the function by "d.Base::get()" (that _should_ work, though I hardly use that syntax); (2) get a pointer to 'd', cast that to a base pointer, and then call get() on it.
Regards,
Robert
Actually, virtual functions are used to enable polymorphism and
calling
member functions of derived class object via base class objects
(pointers and references). If you want to call base class member
functions
through derived class object use something like this:
class Base {
public:
int get() { cout << "I am in base\n"; return 9; }
};
class Derived : public Base {
public:
int get() { return Base::get(); } // call base class members
};
int main()
{
Derived d;
d.get();
return 0;
}
d.base::get();
> without using virtual.
I think you may have misunderstood 'virtual'; it sort of goes the other way.
Cheers & hth.,
- Alf