Click here to Skip to main content
14,639,066 members
Rate this:
Please Sign up or sign in to vote.
See more:
The getters return garbage data even though the "Person" instance seems to contain the right data when I check in the debugger:

Name: P÷        ☺, Age: 2019912769

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

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

#include <string>

using string = std::string;

class Person
    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; }

    string name;
    int age;

What I have tried:

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

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

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
std::cout << "Name: " << person->getName() << " Age: " << person->getAge() << std::endl;

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

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100