Reputation: 386
I have a problem, I have this base class:
class A{
public:
/*...*/
virtual void print() = 0;
};
And here I make one class which inherits from class "A"
class B : public A{
private:
double a;
public:
/*...*/
B(double _a) : a(_a){ }
void print() override{
cout << a<<'\n';
}
};
And I use:
int main(){
/*...*/
std::vector<A*> vec;
/* ... Here I added new object */
vec.push_back(new B(2));
for(__typeof(vec.begin()) it = (vec.begin()); it!= vec.end(); it++){
}
//How to using and display function print which is declared inside class B
}
Question: How to call function print
which is declared inside class B?
I have tried using following method but this notation don't give me a good result:
vec.front()->print();
Upvotes: 0
Views: 384
Reputation: 39404
Your main
just needs to be like this:
int main(){
std::vector<A*> vec;
/* ... Here I added new object */
vec.push_back(new B(2));
for(std::vector<A*>::iterator it = vec.begin(), end = vec.end(); it != end; ++it){
(*it)->print();
}
return 0;
}
Note how the iterator is dereferenced inside the loop.
Upvotes: 5
Reputation: 15334
In your loop you need to dereference the iterator and the contained pointer. So write something like:
(*it)->print();
But you might want to consider a C++11 ranged-based for loop instead:
for (auto ptr : vec)
ptr->print();
Upvotes: 2