1

I was wondering if someone could please illuminate me on why the below code does not behave the way I expect. By that I mean I expect the line

std::cout << myEngine.getDesc() << std::endl;

to print out: "Desc1"

But I get an empty string? I figured that maybe it was because I was splitting up my rudimentary code into different files incorrectly but I get the same thing when I put all the code into one file.

StringErrorTest.cpp

#include <iostream>
#include "Engine.h"


int main()
{
    std::cout << "Compiling & Running!";
    Engine myEngine;
    std::string t1 = "Hello ";
    std::cout << myEngine.getDesc() << std::endl;
    std::cout << t1 << std::endl;
    return 0;
}

Engine.h

#include <string>

class Engine {
private:
    std::string m_Description;
    std::string m_Description2;

public:
    Engine();
    std::string getDesc();
    void setDesc(std::string desc);
    std::string getDesc2();
    void setDesc2(std::string desc2);
    std::string spitItOut();

};

Engine.cpp

#include "Engine.h"

Engine::Engine()
{
    std::string m_Description = "Desc1";
    std::string m_Description2 = "Desc2";
}

std::string Engine::getDesc()
{
    return m_Description;
}

std::string Engine::getDesc2()
{
    return m_Description2;
}

By the way I did search for similar questions but they were all a bit more complex than mine. I feel I have a very basic misunderstanding going on here.

1
  • 1
    In your constructor you define local variable m_Description. Change std::string m_Description = "Desc1"; to m_Description = "Desc1"; (i.e. remove std::string part). Commented Mar 16, 2020 at 7:51

1 Answer 1

4

In Engine::Engine(), you're creating two local objects named m_Description and m_Description2, which have nothing to do with the data members with same names; they hide the names of data members.

What you want to is to assign them as

Engine::Engine()
{
    m_Description = "Desc1";  // or this->m_Description = "Desc1"
    m_Description2 = "Desc2"; // or this->m_Description2 = "Desc2"
}

Or initialize them as

Engine::Engine() : m_Description("Desc1"), m_Description2("Desc2")
{
}
Sign up to request clarification or add additional context in comments.

2 Comments

I understand now.. thank you so much. I'm sorry for such a silly question.
@yoonsi Since this answers your question, you can accept the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.