'String as a parameter in a constructor in C++
class example {
private:
char Name[100];
public:
example() { strcpy(Name, "no_name_yet"); }
example(char n[100]) { strcpy(Name, n); }
};
int main() {
example ex;
char n[100];
cout<<"Give name ";
cin>>n;
example();
}
I want to use the constructor with the parameter so that when the user gives a name it gets copied to the name variable. How can I use the constructor with the parameter instead of the default one? I tried
example(n)
example(char n)
example(*n)
example(n[100])
but none of them work.
Solution 1:[1]
Easy:
#include <string>
#include <iostream>
class example {
private:
std::string name;
public:
example() : name("no name yet"){}
example(std::string const& n) : name(n){}
};
int main() {
example ex;
std::string n;
std::cout << "Give name ";
std::cin >> n;
example ex(n); // you have to give your instance a name, "ex" here
// and actually pass the contructor parameter
}
Solution 2:[2]
It is example my_instance_of_example(n).
I must note, however, that using char arrays for strings is not what you do in C++. You should use std::string instead, it gives you a lot more flexibility.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Xeo |
| Solution 2 | Sergey Kalinichenko |
