System
System

Reputation: 241

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.

Upvotes: 2

Views: 26030

Answers (2)

Xeo
Xeo

Reputation: 131887

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
}

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727027

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.

Upvotes: 2

Related Questions