vendredi 4 août 2017

Object loses data of its members when referred to as pointer to parent class

This program's output is missing the intended values for name and Some string.

Name: , Age: 4, Some string:

Name: , Age: 3, Some string:

If I dynamically allocate memory for each item for myVector in Source.cpp then it works out okay. I'm just wondering why this works out as it does, and what mistakes I have made.

Worth noting is I'm using Visual Studio 2015 C++ compiler.

Parent.h

#pragma once

#include <string>

class Parent
{
public:
    explicit Parent(std::string name, int age)
        : m_name(name), m_age(age) {};

    virtual const std::string toString() const
    {
        return "Name: " + m_name + ", Age: " + std::to_string(m_age);
    }

private:
    std::string m_name;
    int m_age;
};

Child.h

#pragma once

#include "Parent.h"

class Child : public Parent
{
public:
    explicit Child(std::string name, int age, std::string someString)
        : Parent(name, age), m_someString(someString) {};

    virtual const std::string toString() const
    {
        return Parent::toString() + ", Some string: " + m_someString;
    }
private:
    std::string m_someString;
};

Source.cpp

#include <vector>
#include <iostream>

#include "Parent.h"
#include "Child.h"

int main()
{
    std::vector<Parent*> myVector;

    myVector.push_back(&Child("Foo", 4, "Test"));
    myVector.push_back(&Child("Bar", 3, "Test"));

    for (auto p : myVector)
    {
        std::cout << p->toString() << std::endl;
    }

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire