Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8660389
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T16:14:30+00:00 2026-06-12T16:14:30+00:00

I am creating a vector that contains pointers to a base class. In this

  • 0

I am creating a vector that contains pointers to a base class. In this vector I’m dynamically storing pointers to derived classes which contain some member variables, one of them being a string variable name.

#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 a main function. The problem is when I try to output the contents of the member variables, all of them show up except for the string name.
Now, I’ve checked to make sure that the string gets set before calling the PrintContent() method, and it shows that the value is in the vector. However, when I debug through the code, the value is no longer there, instead containing an empty string.

Could 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)
                        {   
                            //fish
                            fishObject fish;
                            fish.setName(name);
                            fish.setDiameter(diameter);
                            fish.setDirection(direction);

                            dimension = fishDimension;
                            fishDimension += 50;
                            fish.setDimension(dimension);
                            fish.setMovingSpeed(0.1);
                            data.push_back(&fish);
                        }
                        else if (diameter >= 10 < 500)
                        {
                            //animal
                            animalObject animal;
                            animal.setName(name);
                            animal.setDiameter(diameter);
                            animal.setDirection(direction);

                            dimension = animalDimension;
                            animalDimension += 800;
                            animal.setDimension(dimension);
                            animal.setMovingSpeed(5.0); 
                            data.push_back(&animal);
                        }
                        else if (diameter >=500)
                        {
                            //star
                            starObject star;
                            star.setName(name);
                            star.setDiameter(diameter);
                            star.setDirection(direction);

                            dimension = starDimension;
                            starDimension += 5000;
                            star.setDimension(dimension);
                            star.setMovingSpeed(30.0);
                            data.push_back(&star);
                        }

                    }
                    else
                    {
                        throw (IncompleteData(name));
                    }
                }
            }
            catch (IncompleteData e)
            {
                std::cerr << "No diameter or direction given for object " << e.objectName << "\n";
            }
        }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T16:14:31+00:00Added an answer on June 12, 2026 at 4:14 pm

    The objects you push to the data vector are local because they are declared inside if/else blocks (see the declarations of fish and animal).

    When you push the address of such an object to the vector, it will continue to point to the local object, which ceases to exist at the end of the local scope. You need to create objects that live beyond the local scope. One way of doing this is to create copies of the local objects on the heap and push those to the vector:

    data.push_back(new fishObject(fish));
    

    Of course this means that you get a memory leak unless you make sure you explicitly delete the elements of the vector some time before the end of the program. The usual recommendation to avoid having to think of this is to use a vector of std::unique_ptr<MovingObject> instead of a vector of naked pointers.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm creating a Vector class, which can basically hold three numerical values. However, a
I have a class that contains a dynamically allocated array, say class A {
Coming from a C# Background I never used any pointers. I'm creating a vector
I have a problem creating a std::map<int, int> from a vector of pointers, called
When creating functions that use strsplit , vector inputs do not behave as desired,
I am creating a windows app that uses a vector of stings as a
I wish for a class A to contain some data, and class B will
I'm creating a new class that inherits queue from the STL library. The only
I am creating a templated Vector class, however, when comparing its use to something
I'm creating a huge matrix that is stored inside nested vectors: typedef vector<vector<pair<unsigned int,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.