• Advertisement
Sign in to follow this  

c++ passing child classes for base classes

This topic is 4222 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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);

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Yes, ChildClass "IS A" BaseClass, so anywhere you can use a base class you can use a child class instead...

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement