Class extStrSet inherits from class strSet. The following function down-casts from the former to the latter.
inline extStrSet& ss2extss (const strSet& ss)
{ return (extStrSet)&ss ; }
Can someone explain how the down-casting is accomplished by explaining each part of the expression in the return statement?
Also why is downcasting so dangerous, is it because of the additions of new variables and functions?

The code isn't even correct as written, but what the line in question says is:

  • take the argument ss, which is a const-reference to the passed object (meaning we're promising not to change the original object, even though we're looking at it)
  • use the & operator to create a pointer to it, so we now have an object of type strSet *
  • finally cast that to type extStrSet, which doesn't make sense since you can't sensibly cast a pointer-to-a-type back to just-that-type

Also, the input to the function has been declared const but the output hasn't, which probably won't compile since it's handing back, again, a reference to the original object. Once you want it const, you should definitely keep it const. :)

As you deduced, the problem with "down-casting" is that the subclass presumably adds more members (which aren't initialized in the casting process), so the resulting object may not behave as expected. I've seen some fascinating trickery accomplished with similar techniques, but it's very hard to guess what's going to be done with an object, and whether to expect it to work. Instead of "down-casting", you can replace that operation with a constructor for the derived class, which takes an instance of the parent class as an argument, and initializes all the members appropriately.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.