Accessing base class method using derived class object

Accessing base class method using derived class object

Post by srini4vasa » Fri, 27 Jul 2007 20:54:38


#include<iostream>
using namespace std;

class A
{
public:
void display()
{
cout<<"A display"<<endl;
}

};

class B : public A
{
public:
void display()
{
cout<<" B display "<<endl;
}
};

int main()
{
B b1;
b1.display();

return 0;
}

In this program can you please tell me how can i access base class
method ie.,display() using derived class object.ie.,b1.

A single line has to be included in this main funtion.
 
 
 

Accessing base class method using derived class object

Post by srini4vasa » Fri, 27 Jul 2007 21:04:12

#include<iostream>
using namespace std;

class A
{
public:
void display()
{
cout<<"A display"<<endl;
}

};

class B : public A
{
public:
void display()
{
cout<<" B display "<<endl;
}
};

int main()
{
B b1;
b1.display();

return 0;
}

In this program can you please tell me how can i access base class
method ie.,display() using derived class object.ie.,b1.

A single line has to be included in this main funtion.

 
 
 

Accessing base class method using derived class object

Post by Phill W » Sat, 28 Jul 2007 20:53:34


Sounds decidedly home-work-ish to me, but what the hey...


/If/ B.display() shadows A.display(), i.e. there's no overriding
involved - my C++ is a /little/ rusty ;-) - then you can do this
directly.
Simply tell ("up-cast") 'B' to behave as if it were an 'A'.

((A)b1).display();

However, if B.display() /overrides/ A.display() - don't think this is
the case, but just for completeness - then you're stuck.
Unless you expose an alternative method on 'B' that calls the base
implementation in 'A', then you can't access the base implementation in
A; and that's as it should be.

HTH,
Phill W.
 
 
 

Accessing base class method using derived class object

Post by Ben Voigt » Sat, 04 Aug 2007 02:36:04


There's no "virtual", so no dynamic dispatch. Calling through a reference
to A will call the base implementation.