Calling derived class method from a pointer to its base class

Hello again.

I was wondering if there is a way to call a derived class method from a pointer to its base class.

Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Class1 {
};

class Class2 : public Class1 {
  public:
    void eat_cheese() {
      // Eat some cheese
    }
};

int main() {
  Class1* someObject = new Class2;
  
  // This will give an error stating that there is no eat_cheese method in Class1
  someObject->eat_cheese();
}


EDIT:

* Can't use virtual functions, btw

Also, IF this even is possible, is it bad practice to do so?
Last edited on
The only way to do it without virtual functions is to downcast:

1
2
3
4
5
6
7
Class1* someObject = new Class2;

//...

Class2* p = dynamic_cast<Class2*>(someObject); // or static_cast if you're 100% sure
if(p)
  p->eat_cheese();


But also note that dynamic_cast will only work if the class is polymorphic (has at least 1 virtual function or a parent that is polymorphic). If neither of those are the case then you'll have to roll the dice and static_cast.

The reason it has to be done like this is because if you have a Class1 pointer, the compiler has no way to know that it actually points to a Class2. It might point to a Class1 or some other derived class which doesn't have the eat_cheese function.

And yes... downcasting is usually bad practice. If you know you will always have a Class2 object, then just use a Class2 pointer.
Ok, the reason why I wanted to do this is because I have an array of pointers to 'Class1' but none of the pointers actually point to the Class1 object. They are all children of it.
Sounds like a design flaw.

If you can't treat all of them the same way then you shouldn't be storing them in a container that suggests they're all the same.

The whole point of inheritance is so that you use different types with common interface. IE: the parent class provides a [virtual] interface, and the child classes implement the behavior specific to their needs.

If you don't have virtual functions, and don't have a common interface... then there's very little reason to use inheritance.
Mh... I thought about other ways I could do what I need to do, and makes a lot more sense to not do it the way I was thinking about at first.

Thanks for the tips.
Topic archived. No new replies allowed.