#include %26lt;iostream%26gt;
using namespace std;
class base{
int i;
public:
void set_i(int num){i=num;}
int get_i(){ return i;}
};
class derived:public base{
int j;
public:
virtual void set_j(int num){j=num;}
int get_j(){ return j;}
};
void main(){
base *bp;
derived d;
bp=%26amp;d;
bp-%26gt;set_i(10);
bp-%26gt;set_j(20); // compiler complains
cout%26lt;%26lt;bp-%26gt;get_i();
cout%26lt;%26lt;bp-%26gt;get_j();// compiler complains
}
In the above mentioned C++ program, can someone guide me why compiler complains on those two lines when I have assigned the address of the deriver class object to pointer of base class? Also, what code should I write to access that method of derived class using pointers?
Thanks in advance.
ss
Doubt about pointers..?
well, bp is a base pointer. and class base doesn't have set_j() and get_j(), therefore it complains.
if you call d.set_j() or d.get_j(), then it works. but you always need either an object or a pointer to an object of class 'derived' to call set_j or get_j.
Reply://They way you program, you should tell the compiler explicitly that you want to access a particuler class method, i think you should read about inheritance.
void main(){
base *bp = new derived();
bp-%26gt;set_i(10); // it will only access base class method
((derived*)bp)-%26gt;set_j(20); // it will access derived class mthod
((derived*)bp)-%26gt;set_i(30);// it will access inherited method in derived class
cout%26lt;%26lt;bp-%26gt;get_i();// it will only access base class method
cout%26lt;%26lt;((derived*)bp)-%26gt;get_j();// it will access derived class mthod
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment