0

I have a constructor for a Person class called "Person" it looks like this:

    Person(const char * their_name, const char * email, int day, int month, int year)
        : name(0), email_address(0), birthday(day, month, year) {

        name = new char [strlen(their_name)+1];
        strcpy_s(name, strlen(their_name) +1, their_name);

        email_address = new char[strlen(email) + 1]; 
        strcpy_s(email_address, strlen(email) + 1, email); 

        cout << "\nPerson(...) FIRST CONSTRUCTOR CREATING: "<<name<<"\n";
        printOn(cout);
    }

I have private variables in this class:

private: 
    char * name; 
    char * email_address; 
    Date birthday; 

I think there is an off by 1 error or something in here, because when I test my constructor like this in main:

Person *p1 = new Person("Sarah", "iam@awesome.com", 2,2,1000);

this prints to my console:

Person(...) FIRST CONSTRUCTOR CREATING: Sarah
ààà

I don't understand why it is printing the a's after the constructor runs... Can anyone see the issue?

EDIT: My printOn method

/*print person on output stream o*/
    virtual void printOn(ostream & o) const { 
        //print person
         o << "………";
    } 

and overriden << operator

ostream & operator<<(ostream & ostr, const Person & p) { 
    p.printOn(ostr); 
    return ostr; 
} 
Sarah
  • 2,713
  • 13
  • 31
  • 45

2 Answers2

0

It is not clear what function printOn(cout); does in your constructor. Can it be that it is its output?

As for function strcpy_s then there is no any need to use it. It would be much better to use old function strcpy. In your code you call strlen twice: one time when you allocate memory and the second time when you use strcpy_s.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Good call, I commented out the printOn(cout) line and it went away. – Sarah Oct 30 '13 at 19:36
  • "No need to use `strcpy_s`"? The only way I agree with that is if the suggestion was to use `std::string` instead of using `strcpy`. – crashmstr Oct 30 '13 at 19:47
  • @crashmstr - it's pointless to use `strcpy_s` when the code has just allocated a buffer that is the right size. Writing correct code is not a matter of applying simplistic formulae, but of thinking about what the code is doing. – Pete Becker Oct 30 '13 at 20:30
0

Your output is using a different text encoding than your editor is. The character that shows as in your code editor becomes à when you print it out.

In general, don't use high-ASCII characters unless you know how to choose the proper encoding, otherwise things won't work the way you think.

AnotherParker
  • 789
  • 5
  • 16