Click here to Skip to main content
15,892,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
The getters return garbage data even though the "Person" instance seems to contain the right data when I check in the debugger:

C++
Name: P÷        ☺, Age: 2019912769


C++
std::unique_ptr<Person> person(new Person());

printf("Name: %s, Age: %d\n", person->getName(), person->getAge());

C++
#include <string>

using string = std::string;

class Person
{
public:
    Person() : name("Alex"), age(22) { }
    
    void change(const string& name, const int age)
    {
        this->name = name;
        this->age = age;
    }

    const string getName() { return name; }
    const int getAge() { return age; }

private:
    string name;
    int age;
};


What I have tried:

Searching the internet for an explanation why this happens
Posted
Updated 14-Jul-17 6:35am

1 solution

C++ programs should probably use std::cout rather than printf. In this case, the format specifier '%s' expects an char * not a C++ string.

You should get the right results with
C++
std::cout << "Name: " << person->getName() << " Age: " << person->getAge() << std::endl;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900