V
V
Vasily Demin2016-02-23 22:45:54
OOP
Vasily Demin, 2016-02-23 22:45:54

How to make a base class object or pointer that can access all child class methods?

I have a base wall class that has coordinates and a texture, and a child class called door that has coordinates, a texture, and an open method. I have a vector with objects of the wall type, in which there are objects of the door type, I need to call the open method from this vector for all objects of the door class.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Moseychuk, 2016-02-24
@includedlibrary

Bundle typeid+dynamic_cast

#include <iostream>
#include <vector>
#include <random>
#include <typeinfo>

using namespace std;

class Foo {
  public:
    virtual ~Foo(){}
};

class Bar: public Foo {
  private:
    size_t c;
    static size_t n;
  
  public:
    Bar(): c(n++){};
    virtual ~Bar(){};
    size_t getC() const {return c;};
};

size_t Bar::n(0);

int main() {
  
    std::mt19937 gen;
    std::uniform_int_distribution<unsigned> dis(0, 2);
    
    vector<Foo*> vec;
    
    for(size_t i = 0; i < 100; ++i) {
    	if(dis(gen))
    		vec.push_back(new Foo);
    	else
    		vec.push_back(new Bar);
    }
    
    for(auto p: vec) {
    	if(typeid(*p) == typeid(Bar))
    		cout << dynamic_cast<Bar*>(p)->getC() << endl;
    }
    
     for(auto p: vec)
     	delete p;
  
  return 0;
}

You can get away with one dynamic_cast, but then you have to handle exceptions.

R
res2001, 2016-02-24
@res2001

In wall, make a virtual open method with a trivial implementation (for example, retrurn 0;), which you then override in door.
When a virtual method is called by a pointer/reference to the base class, the method of the corresponding child class will be called without dancing with a tambourine.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question