0

I'm trying to learn c ++, doing some tests, I have the following questions, which, in a way shows one thing and the other works as expected, I will try to explain as best I can, "sorry for my English," I have a base class that is more or less so I think this is the important part;

class Basefptr {
public:
    Basefptr();
    virtual ~Basefptr();
    virtual void funcPtr1();
};

inline void Basefptr::funcPtr1(){
    std::cout << "funcPtr1" << std::endl;
}
#endif /* BASEFPTR_H_ */

and in the derived class that other;

#include "Basefptr.h"

class Derivada : public Basefptr {
public:
    Derivada();
    virtual ~Derivada();
    virtual void funcPtr1();
};

inline void Derivada::funcPtr1(){
    std::cout << "funcPtr1_de_Derivada" << std::endl;
}
#endif /* DERIVADA_H_ */

that this is the main;

#include "Basefptr.h"
#include "Derivada.h"
#include <vector>
#include <algorithm>

int main(int argc, char* argv[]){

Basefptr* base     = new Basefptr;
Derivada* derivada = new Derivada;

std::vector<Basefptr*> poli;

poli.push_back(base);
poli.push_back(derivada);


std::for_each(poli.begin(), poli.end(),[](Basefptr* b){

    b->funcPtr1();
});


Basefptr base1;
Derivada derivada1;

std::vector<Basefptr> poli1;

poli1.push_back(base1);
poli1.push_back(derivada1);


std::for_each(poli1.begin(), poli1.end(),[](Basefptr b){

    b.funcPtr1();
});

return 0;
}

this the shell out;

 funcPtr1 
 funcPtr1_de_Derivada

 funcPtr1 
 funcPtr1

The first two lines are as expected, but the second is not what I expected, because he believed that would be like the first, can someone explain me, the reason this is so, if you please. or am I doing something wrong greetings and thanks for reading.

Angel Angel
  • 19,670
  • 29
  • 79
  • 105

1 Answers1

3

The line

std::vector<Basefptr> poli1;

Tells the vector to hold objects of type Basefptr. When you

poli1.push_back(base1);
poli1.push_back(derivada1);

The vector is creating new objects with a Basefptr constructor, that it owns itself. These are not the objects you created.

Captain Giraffe
  • 14,407
  • 6
  • 39
  • 67
  • to clear you truly logical, thanks for your answer, only I can only upvote, will not let me accept your answer right now but I will in the future thanks – Angel Angel Apr 07 '15 at 10:27