Hi All, I've been banging my head against the wall for a while on this.
I have a parent class and bunch of child classes. I want to store a instance of the child class in another class, then call the child class function. but it keeps using the parent. I've tried passing the child into the container by reference and it doesn't work either..
Here's the details.
In my library header file I have
class Parent {
public:
int get();
};
class ChildA : public Parent {
public:
int get();
};
class Container {
public:
Parent par;
Container( Parent P );
int doit();
};
In my library cpp file i have
int Parent::get(){ return 0; };
int ChildA::get(){ return 1; };
Container::Container(Parent P){
par = P;
};
int Container::doit() {
return par.get();
};
in my arduino ino file in setup() i have
ChildA A = ChildA();
Container C = Container( A );
Serial.print( C.doit() );
The value that I get is 0.
When i want to get 1.
I'm somewhat new to c++ so hopefully this is something easy?
My googling for a solution has failed me to, so i must not be using the right words.
Your object A is both a Parent, and a ChildA. Your Container expects an argument of type Parent, so when you pass object A, Container "sees" the object as type Parent. If you want a Child method to over-ride a Parent method, even when a ChildA object is referenced, you much define the Parent method as virtual.
Google "c++ virtual methods". There are plenty of good tutorials out there that explain the finer points.
@gfvalvo - That all worked great!! Thank you! ...and I understand everything except this
Container::Container(Parent &P): ptr(&P){
It seems like that's assigning the pointer, but it's syntax I don't know. Does it have a name that I could read more about?
@rayLivingston - thanks for the tip. Making those function virtual alone didn't work, but I'll use that and the other answer to go learn about virtual and passing pointers! Thanks for the *pointer.