Classes subclasses question

Hello!
1
2
3
4
5
6
7
8
9
10
class parentclass{

};

class subclass: public parentclass{
void print(){
cout << "Hello";
}

};


Can I somehow then access the subclass methods outside the class?
Like
1
2
3
4
5
6
int main(){
subclass Sub;
vector<parentclass*> AllObjects;
AllObjects.push_back(&Sub);
AllObjects[0]->print();
}

Why won't this work? Why can AllObjects[0] only acces parentclass methods? As I see it, it points towards an object which is a Subclass? So it should work?
Last edited on
A pointer to the base class can't access members from derived classes because there is no way to tell if all classes inheriting from parentClass implement print()
Instead you could put a virtual function in the parentClass, so derived classes will implement it in various ways
Hmm alright:) Thanks
Topic archived. No new replies allowed.