0

Let's imagine a situation where I have an abstract class named 'Base' with a virtual pure method named foo(), and 2 children (Inherited1 and Inherited2) that both implement this method in their own way. Now let's say that one of these children (Inherited1) needs another method called bar() that would make no sense to implement in Inherited2.

In my main, i Have

Base * randomObject = new Inherited1();

I can't access this method using

random->bar();

What should I do. Like I said, it would make no sense to implement it in inherited2, so I can't simply put another virtual method in Base, or should I?

asdfasdf
  • 774
  • 11
  • 29

1 Answers1

2

If you had a variable

Base* randomObject = new Inherited1();

You could cast it down to the base class

Inherited1* foo = static_cast<Inherited1*>(randomObject);
foo->bar();

But you have to be sure that the pointer is indeed of that derived class otherwise static_cast isn't safe. There are a number of ways to do this, such as storing an enum in the derived classes that you can check via a virtual getter, or checking if the result of a dynamic_cast is nullptr, but that is slower.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • Thank you, that was what I was looking for, is it bad practice to do a one time call by doing ? : static_cast(randomObject)->bar(); I know there has to be a design problem in my architecture, but when 10 methods are used by both children class except for one random method, I felt like I had to use polymorphism still – asdfasdf May 12 '15 at 19:42
  • No that will work fine, just make sure that the cast is safe. – Cory Kramer May 12 '15 at 19:47