[SOLVED] Functions/Inheritance

Say I have the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class animal {
public:
  string name;
}

class cat: public animal {
public:
  bool has_tail;
}

class bird: public animal {
public:
  bool has_wings;
}


And I wanted to make a function that took either of the two (cat/bird) classes as a parameter. I heard you can do this with a pointer to the base class and such, but I am unsure of how to go about doing it...is it related to the pure virtual functions in classes and creating pointers to those classes, then pointing them at inheriting classes?

EX:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
void printname(animal* Animal) { //unsure if this is correct
  cout<<Animal->name;
}

int main() {
  cat Cat;
  bird Bird;
  Cat.name = "Catname";
  Bird.name = "Birdname";
  animal* Animal1 = &Cat;
  animal* Animal2 = &Bird;
  printname(Animal1);
  printname(Animal2);
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
void printname(animal &Animal) { //unsure if this is correct
  cout<<Animal.name;
}

int main() {
  cat Cat();
  bird Bird();
  Cat.name = "Catname";
  Bird.name = "Birdname";
  printname(Cat);
  printname(Bird);
}


Should work fine.

Then google
- inheritence
- polymorphism
- virtual
- pure virtual
- abstract data type
Last edited on
Got it! Thanks!
Topic archived. No new replies allowed.