Inheritance and Overloading

L

Larry Lindsey

If I have classes Parent, Child, and Seat as follows

class Parent{
public:
float getValue(){return 0;}
...
}

class Child: public Parent{
public:
float getValue(){return val;}
...
private:
float val;
}

class Seat{
public:
Parent* getPerson(){
return thePerson;
}
void setPerson(Parent *inPerson){
thePerson=inPerson;
}
...
private:
Parent* thePerson;
}

If i do this:

Child *c = new Child();
Seat *s = new Seat();
Child->setValue(12);
s->setPerson(c);

How would I make s->getPerson()->getValue() return 12, and not 0?

--Larry
 
J

jeffc

Larry Lindsey said:
If I have classes Parent, Child, and Seat as follows

class Parent{
public:
float getValue(){return 0;}
...
}

class Child: public Parent{
public:
float getValue(){return val;}
...
private:
float val;
}

class Seat{
public:
Parent* getPerson(){
return thePerson;
}
void setPerson(Parent *inPerson){
thePerson=inPerson;
}
...
private:
Parent* thePerson;
}

If i do this:

Child *c = new Child();
Seat *s = new Seat();
Child->setValue(12);

Did you forget to define this function?
s->setPerson(c);

How would I make s->getPerson()->getValue() return 12, and not 0?

Read up on virtual functions.
 
R

red floyd

jeffc said:
Did you forget to define this function?




Read up on virtual functions.
In other words, because Parent::getValue() is non-virtual, and getPerson
returns a Parent*, any reference to getValue() through getPerson() will access
Parent::getValue().

If you declare getValue() as virtual in Parent(), then it will behave in the
polymorphic manner that you desire.
 
L

Larry Lindsey

red floyd said:
In other words, because Parent::getValue() is non-virtual, and getPerson
returns a Parent*, any reference to getValue() through getPerson() will access
Parent::getValue().

If you declare getValue() as virtual in Parent(), then it will behave in the
polymorphic manner that you desire.

I've made everything virtual that needs to be virtual, but now I'm having a
problem where private variables aren't keeping their values. Does anyone
know whats going on?

for instance, in the above example, after I call c->setValue(12), were I to
call c->getValue(), it would return -8.4873e+008, which I'm pretty sure is
2's complement 0x000000 for some number of 0's.

Thanks for all of you help thus far, btw.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top