the5thace
the5thace

Reputation: 159

How to turn a string passed through a constructor in to a variable?

One of my current projects requires me to send an actual name of a file into a class but I can't figure out how to turn the string into a variable. In other words I need to turn Andrew in to the variable name in the Person class.

main.c

#include <iostream>
#include <string>
#include "Person.h" 

using namespace std;

int main ()
{
Person p1("Andrew");

}

Person.h

 #include <iostream>

 using namespace std;

 class Person 
 {
 public:
    Person (string name);
    void setName(string name) {string name = name;}
    void printName(string name) {cout << name;} 
private:
    string name; 
  };

Upvotes: 1

Views: 2651

Answers (4)

Siavash
Siavash

Reputation: 7853

you need to perform {string name = name;} inside your constructor, not in set name.

so :

 class Person 
 {

 public:
    Person (string name) { this->name = name;}

    void printName(string name) {cout << name;} 
 private:
    string name; 
  };

and I would use different variable names like name and my_name so there are no confusions.

Upvotes: 1

A human being
A human being

Reputation: 1220

In the constructor of Person, do this:

Person (string name)
{
   this->name = name;
}

or

you can use member initialization list:

Person(string name)
: name(name) {}

or

you can just call your function setName in the constructor

Upvotes: 1

Joseph Mansfield
Joseph Mansfield

Reputation: 110658

First of all, note that here you are declaring a variable local to setName and simply assigning it to itself:

void setName(string name) {string name = name;}

The member name is left unaffected. You instead want:

void setName(string name) { this->name = name; }

You can do very much the same with the constructor:

Person (string name) { this->name = name; }

However, this has a little issue. When you create a Person object, the name member will first be constructed as an empty string and then assigned to. That's completely pointless. It'd be great if we could construct it with the value given by the argument straight away. In fact, we can, with a member initialization list:

Person (string name)
  : name(name)
{ }

This basically says "initialize the name member with the name parameter".

You also have a problem with printName. It takes a string argument and then prints that out. It seems more likely that you'd want to print out the name member:

void printName() {cout << name;} 

Upvotes: 7

Nate Hekman
Nate Hekman

Reputation: 6657

Initialize the member variable:

Person(string n) : name(n) {}

Upvotes: 3

Related Questions