c++ passing child classes for base classes

Started by
1 comment, last by GameDev.net 17 years, 9 months ago
Is it valid in C++ like in Java to pass a child class as a base class? Example below:
class Baseclass { };

class Childclass : public Baseclass { };

void do_stuff(Baseclass *b) {
  // do stuff
}

int main() {
  Childclass *a = new Childclass;
  do_stuff(a);
  return 0;
}
In addition is it possible to create a blank pointer to a baseclass and set it to a new instnace of a child class. Another example below:
int main() {
  Baseclass *a;
  a = new Childclass;
  return 0;
}
If neither of these cases are possible, are there workarounds? Thanks a bunch.
Advertisement
Yes, C++ supports polymorphism, just like Java does.

Childclass *a = new Childclass();
Baseclass *b = new Childclass();

You can even go backwards and convert the base class pointer to derived class pointer:

Baseclass *b = new Childclass();
Childclass *c = dynamic_cast<Childclass*>(b);
deathkrushPS3/Xbox360 Graphics Programmer, Mass Media.Completed Projects: Stuntman Ignition (PS3), Saints Row 2 (PS3), Darksiders(PS3, 360)
Yes, ChildClass "IS A" BaseClass, so anywhere you can use a base class you can use a child class instead...

This topic is closed to new replies.

Advertisement