I'm on a C++ project that needs a vector of Derived classes, to go over it and call a method from the base class. For that, I did:
--Edit:
class BaseClass {
private:
float attribute1;
float attribute2;
public:
constructor;
virtual destructor;
virtual float virtualMethod() { return (getter1() + getter2()*getter1());}
protected:
virtual float getter1();
virtual float getter2();
}
Derived classes only have their own attributes and getters:
DerivedClassA : public BaseClass {
private:
std::string att1A;
std::string att2A;
int att3A;
public:
constructor;
virtual destructor;
protected:
//getters for att1,att2 and att3;
}
DerivedClassB : public BaseClass {
private:
std::string att1B;
std::float att2B;
int att3B;
public:
constructor;
virtual destructor;
protected:
//getters for att1,att2 and att3;
}
vector<BaseClass*> vector;
BaseClass *object1 = new DerivedClassA(string, string, int, float, float);
BaseClass *object2 = new DerivedClassB(string, float, float, float);
vector.push_back(object1);
vector.push_back(object2);
for (int i=0; i<vector.size(); i++) { cout << vector[i]->virtualMethod() << endl; } //virtualMethod returns a float.
The desired behavior is: when i create the object from the Derived Classes i give them some values. The interest ones are the 2 last floats in this case. The virtualMethod calls their values and complete the operation: firstfloat + secondfloat*firstfloat
and show the return value.
When I try to run it, the program crashes in the virtualMethod
call. Am I doing something wrong? I looked for some answers in another examples but they are more or less like this and I even try with iterator and nothing. Thanks!