I am creating a vector containing pointers to a base class. In this vector, I dynamically store pointers to derived classes that contain some member variables, one of which is the name of a string variable.
#include "stdafx.h" #include <iostream> #include <vector> #include <string> #include <cstdlib> bool hasDirection = false; bool hasDiameter = false; int direction; float diameter; int starDimension = 0; int animalDimension = 0; int fishDimension = 0; class MovingObject { protected: std::string name; int direction; float diameter; int dimension; float movingSpeed; public: std::string getName(){ return name;}; int getDirection(){ return direction;}; float getDiameter(){ return diameter;}; float getMovingSpeed(){ return movingSpeed;}; int getDimension(){ return dimension;}; void setName(std::string v){ name = v;}; void setDirection(int d){ direction = d;}; void setDiameter(float f){ diameter = f;}; void setMovingSpeed(float s){ movingSpeed = s;}; void setDimension (int d){ dimension = d;}; virtual void PrintContents()=0; }; static std::vector<MovingObject*> data; class starObject : public MovingObject { public: void PrintContents() { std::cout << "(" << getName() << "," << getDiameter() << "," << getDirection() << ")"; } }; class animalObject : public MovingObject { public: void PrintContents() { std::cout << "(" << getName() << "," << getDiameter() << "," << getDirection() << ")"; } }; class fishObject : public MovingObject { public: void PrintContents() { std::cout << "(" << getName() << "," << getDiameter() << "," << getDirection() << ", [" << getDimension() << "], " << getMovingSpeed() << ")"; } };
I later set all these member variables inside the main function. The problem is that when I try to display the contents of member variables, all of them are displayed except for the string name. Now I checked that the string was set before calling the PrintContent () method, and it shows that the value is in the vector. However, when I debug the code, the value no longer exists, instead it contains an empty string.
Can someone with better C ++ knowledge explain to me why this is happening? This is the main class:
int main() { std::string type; Reader reader; while (!std::cin.eof()) { try { std::string type; std::cin >> type; if (type =="int") { reader.ReadDirection(); } else if (type =="float") { reader.ReadDiameter(); } else if (type == "string") { std::string name; std::cin >> name; if (hasDirection && hasDiameter) { int dimension; if (diameter > 0 && diameter < 10) {
source share