thanesh
asked on
Inhertiance question
Hi Experts,
I have been having some strange things happening in my code. It worked one or two times and not after. I began to doubt there is some problem in the way I am using inheritance/polimorphism. here is the simplified version of the code. Am I doing something wrong? I tried this in visual studio 6.0 and it seems to work all the time.( Printing 3)
#include <iostream>
using namespace std;
class A
{
public:
A() {};
~A() {};
virtual int getMember(){ return 0;};
virtual void setMember(int i ) { memA = 0;};
private:
int memA;
};
class B : public A
{
public:
B(){ };
~B(){ };
int getMember(){return memB;};
void setMember(int a){ memB = a; };
private:
int memB;
};
class X
{
public:
X(){};
~X(){};
void setSomething(A& a){ cout << a.getMember() << endl;};
};
int main()
{
X *xx = new X();
B *ab = new B();
ab->setMember(3);
xx->setSomething(*ab);
return 0;
}
I have been having some strange things happening in my code. It worked one or two times and not after. I began to doubt there is some problem in the way I am using inheritance/polimorphism. here is the simplified version of the code. Am I doing something wrong? I tried this in visual studio 6.0 and it seems to work all the time.( Printing 3)
#include <iostream>
using namespace std;
class A
{
public:
A() {};
~A() {};
virtual int getMember(){ return 0;};
virtual void setMember(int i ) { memA = 0;};
private:
int memA;
};
class B : public A
{
public:
B(){ };
~B(){ };
int getMember(){return memB;};
void setMember(int a){ memB = a; };
private:
int memB;
};
class X
{
public:
X(){};
~X(){};
void setSomething(A& a){ cout << a.getMember() << endl;};
};
int main()
{
X *xx = new X();
B *ab = new B();
ab->setMember(3);
xx->setSomething(*ab);
return 0;
}
This is absolutely OK. Since 'getMember()' is declared virtual, 'X::setSomething()' will call 'B:getMember()' through the virtual function table.
ASKER
Thanks JKR. Am I using the pointers correctly. Because, I would like to confirm this before I deal with my rest of the code.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.