Question

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; 
} 
Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top