Take the 2-minute tour ×
class example {
    char Name[100];        

     example(){strcpy(Name, "no_name_yet");}
     example(char n[100]){strcpy(Name, n);}


int main() {
     example ex;
     char n[100];

     cout<<"Give name ";

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 constructoe with the parameter instead of the default one? I tried

example(char n)

but none of them work...

share|improve this question
It should be pointed out to you, that as a parameter, char n[100] is identical to char n[99], char n[] and char * n. That is to say, the actual parameter type is pointer to char, and the number is ignored. –  Benjamin Lindley Dec 17 '11 at 19:32

2 Answers 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.

share|improve this answer
if i do example ex(n) it says that example ex was previously declared –  System Dec 17 '11 at 18:29
That's because you already declared (and constructed it) right at the beginning of main. You need to declare it once only. –  David Heffernan Dec 17 '11 at 18:31
this worked but what if I wanted to use the ex object somewhere before in main so I needed to declare it at the beginning? –  System Dec 17 '11 at 18:35
@System If you need to use that variable before, then you should use an assignment instead of a constructor. –  dasblinkenlight Dec 17 '11 at 18:37
@dasblinkenlight thanks! –  System Dec 17 '11 at 18:40


#include <string>
#include <iostream>

class example {
    std::string name;

    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
share|improve this answer
can't it be done without using a copy constructor? –  System Dec 17 '11 at 18:28
As a general rule (at least in C++03), if you are going to copy the argument anyway, pass it by value. –  Björn Pollex Dec 17 '11 at 18:29
@Björn: I might aswell do that and use std::move in the ctor, but y'know, I might also just keep it simple. :) –  Xeo Dec 17 '11 at 18:30
@System: What exactly do you mean with that? You are only invoking the copy ctor of std::string here, which is unavoidable. –  Xeo Dec 17 '11 at 18:31
@System: It's best if you get a good book, because those are basic questions about std::string. In general, the memory is consecutive. In the new standard (C++11), it's even promised. –  Xeo Dec 17 '11 at 18:56

Your Answer


