Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

calling base class method from derive class object without virtual

0 views
Skip to first unread message

Tinku

unread,
Jan 31, 2010, 3:39:53 AM1/31/10
to aijaz...@honeywell.com
Hi

#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.


Robert Fendt

unread,
Jan 31, 2010, 3:55:50 AM1/31/10
to
And thus spake Tinku <sumit...@gmail.com>
Sun, 31 Jan 2010 00:39:53 -0800 (PST):

> 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

Saeed Amrollahi

unread,
Jan 31, 2010, 9:28:27 AM1/31/10
to

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;
}

Alf P. Steinbach

unread,
Jan 31, 2010, 9:40:02 AM1/31/10
to
* Tinku:

>
> 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

d.base::get();


> without using virtual.

I think you may have misunderstood 'virtual'; it sort of goes the other way.


Cheers & hth.,

- Alf

0 new messages